【问题标题】:How can i have a base controller that has a prefix route in net core 3如何在 net core 3 中拥有一个具有前缀路由的基本控制器
【发布时间】:2020-04-27 12:09:55
【问题描述】:

实际上我正在使用 .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
    }

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

【问题讨论】:

    标签: c# .net-core asp.net-web-api2


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2020-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-30
      相关资源
      最近更新 更多