簡體   English   中英

ASP.NET Core 3.0 端點路由不適用於默認路由

[英]ASP.NET Core 3.0 Endpoint Routing doesn't work for default route

我已根據此頁面的指南將現有的 API 項目從2.2遷移到3.0

因此我刪除了:

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

並插入:

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

但是沒有 controller 和行動將被綁定。 對於我調用的任何 API,我得到的只是 404。

我應該如何調試它,我在這里錯過了什么?

更新: Startup.cs文件位於另一個程序集中。 我們在許多項目中重復使用一個集中的Startup.cs文件。

屬性路由與傳統路由

為瀏覽器服務 HTML 頁面的控制器使用常規路由,為服務 REST API 的控制器使用屬性路由是典型的。

Build web API 和 ASP.NET 核心:屬性路由要求

[ApiController]屬性使屬性路由成為一項要求。 例如:

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase

通過 Startup.Configure 中的UseEndpointsUseMvcUseMvcWithDefaultRoute定義的常規路由無法訪問操作。

如果要對 web api 使用常規路由,則需要在 web Z8A5DA52ED1026427A8A359 上禁用屬性路由。

啟動:

   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?}");
        });
    }

Web api controller:

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

    //[HttpGet("{id}")]
    public ActionResult<int> GetById(int id)
    {
        return id;
    }
}

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

我可以推薦我的解決方案。

像這樣創建您的自定義基礎 controller。

    [Route("api/[controller]/[action]/{id?}")]
    [ApiController]
    public class CustomBaseController : ControllerBase
    {
    }

並使用 CustomBaseController

 public class TestController : CustomBaseController
    {
        public IActionResult Test()
        {
            return Ok($"Test {DateTime.UtcNow}");
        }
    }

Rout` api/測試/測試

你應該試試:

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });

即使在像UseEndpoints 和 UseMvc這樣的中間件中,它似乎也不支持常規路由你可以在這里找到

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM