如何将“API”前缀添加到asp.netcorewebAPI中的每个端点

wsewodh2  于 2023-02-17  发布在  .NET
关注(0)|答案(4)|浏览(196)

我需要自动添加API/ prefix到我的asp .netcorewebapi的每个端点。怎么做?

qni6mghb

qni6mghb1#

您可以自定义MvcOptionsExtensions以全局设置路由前缀,而不是手动更改路由属性。
1.自定义MvcOptionsExtensions

public static class MvcOptionsExtensions
{
    public static void UseRoutePrefix(this MvcOptions opts, IRouteTemplateProvider routeAttribute)
    {
        opts.Conventions.Add(new RoutePrefixConvention(routeAttribute));
    }

    public static void UseRoutePrefix(this MvcOptions opts, string
    prefix)
    {
        opts.UseRoutePrefix(new RouteAttribute(prefix));
    }
}
public class RoutePrefixConvention : IApplicationModelConvention
{
    private readonly AttributeRouteModel _routePrefix;
    public RoutePrefixConvention(IRouteTemplateProvider route)
    {
        _routePrefix = new AttributeRouteModel(route);
    }
    public void Apply(ApplicationModel application)
    {
        foreach (var selector in application.Controllers.SelectMany(c => c.Selectors))
        {
            if (selector.AttributeRouteModel != null)
            {
                selector.AttributeRouteModel = AttributeRouteModel.CombineAttributeRouteModel(_routePrefix, selector.AttributeRouteModel);
            }
            else
            {
                selector.AttributeRouteModel = _routePrefix;
            }
        }
    }
}

2:在Startup. cs(.Net6之前的版本)或Program. cs(. Net 6之后的版本)中注册:

services.AddControllers(o =>{
    o.UseRoutePrefix("api");
});

或者:

builder.Services.AddControllers(o =>{
    o.UseRoutePrefix("api");
});
xtupzzrd

xtupzzrd2#

使用Route前缀“API/”创建控制器构造函数
例如,假设您的控制器类名为CustomerController

[Route("api/[controller]")]
public class CustomerController : ControllerBase
{

}

// This will become api/customer
[HttpGet]
public async Task<ActionResult> GetCustomers()
{
   // Code to get Customers
}

// This will become api/customer/{id}
[HttpGet]
[Route("{id}")]
public async Task<ActionResult> GetCustomerById(int id)
{
   // Code to get Customer by Id
}
tjvv9vkg

tjvv9vkg3#

我们可以像这样简单地将其添加到控制器的顶部

[Route("api/[controller]")]
public class TestController : ControllerBase
{
    [HttpGet("version")]
    public IActionResult Get()
    {
        return new OkObjectResult("Version One");
    }
   [HttpGet("Types")]
    public IActionResult GetTypes()
    {
        return new OkObjectResult("Type One");
    }
}

以便您可以访问如下内容

....api/Test/version
....api/Test/Types
pw9qyyiw

pw9qyyiw4#

似乎你可以用一个常数。

public static class Consts
{
    public const string DefaultRoute = "api/[controller]";
}

并在任何地方重复使用它。如果你需要在任何地方改变默认路线--只需要改变常量。

[Route(Consts.DefaultRoute)]
public class TestController : ControllerBase
{
...
}

相关问题