首页 > 解决方案 > 如何在 net core 3 中拥有一个具有前缀路由的基本控制器

问题描述

实际上我正在使用.NET Core 3,

我有这样一条路线的控制器:

[ApiController]
[Route("customers/app")]
public class CustomerAppController : ControllerBase
{
}

我想做的是拥有一个基本控制器,我可以在其中为所有控制器放置许多我想要的东西,包括路由前缀,如下所示:

[Route("api/v1/[controller]")]
public class CoreController : ControllerBase
{
    protected virtual Object HandleException(Exception ex, string path, ILogger logger)
    {
        logger.LogError(ex, "Unhandled exception.");
        return StatusCode(5000, new { ex.Message });
    }
}

那么控制器将是:

[ApiController]
[Route("customers/app")]
public class CustomerAppController : CoreController
{

    //TODO: put actions here

    public override Object HandleException(Exception ex, string path, ILogger logger) { }
}

我怎样才能使这项工作?

我发现我可以使用这种方法:

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UsePathBase("/api/v1");
        //other things
    }

现在我可以使用 api 调用我的 api localhost/api/v1/randompath,但如果我使用它也可以使用localhost/randompath

标签: c#.net-coreasp.net-web-api2

解决方案


将 Route attr 添加到您的控制器并在那里设置路径。

[Route("api/v1/[controller]")]
[ApiController]

在您各自的控制器中。我正在使用.net core web api,它通过这种方法对我有用,而不必使用 app.UsePathBase()。如果我将路径设置为 /api/v1/ 我无法通过 url 模式 /api/[Controller] 访问 api 而无需补充 v1。


推荐阅读