ASP.NET Core 3.0 端点路由不适用于默认路由

moh*_*eli 8 c# asp.net-core-3.0

我已根据此页面中的指南将现有 API 项目从 迁移2.2到。3.0

因此我删除了:

app.UseMvc(options =>
{
    options.MapRoute("Default", "{controller=Default}/{action=Index}/{id?}");
});
Run Code Online (Sandbox Code Playgroud)

并插入:

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(name: "Default", pattern: "{controller=Default}/{action=Index}/{id?}");
});
Run Code Online (Sandbox Code Playgroud)

但是不会绑定控制器和操作。对于我调用的任何 API,我得到的只是 404。

我应该如何调试它,我在这里想念什么?

更新:该Startup.cs文件位于另一个程序集中。我们Startup.cs在许多项目中重用一个集中的文件。

Xue*_*hen 8

从属性路由 vs 传统路由:

为浏览器提供 HTML 页面的控制器使用传统路由,为 REST API 提供服务的控制器使用属性路由是典型的做法。

从使用 ASP.NET Core 构建 Web API:属性路由要求:

该[ApiController]属性使属性路由成为一项要求。例如:

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
Run Code Online (Sandbox Code Playgroud)

动作是通过由限定的常规途径不可访问UseEndpoints,UseMvc或UseMvcWithDefaultRoute在Startup.Configure。

如果您想使用 web api 的常规路由,则需要禁用 web api 上的属性路由。

启动:

   public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();
    }

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

        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "Default",
                pattern: "{controller=default}/{action=Index}/{id?}");
        });
    }
Run Code Online (Sandbox Code Playgroud)

Web API 控制器:

 //[Route("api/[controller]")]
//[ApiController]
public class DefaultController : ControllerBase
{
    public  ActionResult<string> Index()
    {
        return "value";
    }

    //[HttpGet("{id}")]
    public ActionResult<int> GetById(int id)
    {
        return id;
    }
}
Run Code Online (Sandbox Code Playgroud)

这可以由 http://localhost:44888/default/getbyid/123