如何在 web api 项目上定义初始 url?

Hat*_*umi 6 c# macos asp.net-mvc visual-studio-code

我在 Mac 上的 Visual Studio Code 上创建了一个项目,并想设置我的默认页面。我在“Startup.cs”上写了代码,但它不起作用。

当我运行项目并打开浏览器时,它显示没有找到控制器。

遵循 Startup.cs 代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace ProblemsV4
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Problem}/{action=Index}");
            });
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Fel*_*sto 3

您应该创建一个MVC 项目以便能够定义初始 URL。

你的问题是因为你正在创建一个Web API项目而不是一个MVC项目,因为它是一个API,有一个默认的初始url是没有意义的,就像MVC项目一样(因为视图),

您可以按照本教程创建 MVC 应用程序并设置默认控制器: https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app-xplat/

  • 他使用的是 ASP.Net Core,所以 MVC 项目或 Web API 项目在这里是相同的:-) (2认同)