【问题标题】:Grouping controllers by custom Attribute in Web API在 Web API 中按自定义属性对控制器进行分组
【发布时间】:2019-12-04 14:29:35
【问题描述】:

我正在尝试通过自定义属性实现控制器的“路由分组”,类似于 ApiVersioning。

我想在我的控制器上拥有什么:

[Authorize]
[RoutePrefix("api/g{group:apiGroup}/v{version:apiVersion}/Authorization")]
public class AuthorizationController : ApiController
{
    [HttpPost]
    [AllowAnonymous]
    [ApiVersion("1.0")]
    [ApiGroup("NAS")] /// <--- MY GROUPING
    [Route("VerifyCredentials")]
    [ResponseType(typeof(ContactPerson))]
    public async Task<IHttpActionResult> VerifyCredentials(Credentials credentials)
    {....}

所以到这个 Api 调用的路由是 localhost/Api/NAS/V1/Authorization

我使用 Microsoft.AspNet.WebApi.Versioning 包成功地进行了版本控制。

我的自定义属性:

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class ApiGroupAttribute : Attribute
{
    public string GroupName { get; private set; }

    public ApiGroupAttribute(string groupName)
    {
        if (string.IsNullOrEmpty(groupName))
        {
            throw new ArgumentNullException("groupName");
        }
        GroupName = groupName;
    }
}

编辑: 我试图用 routeConstraint 来实现这一点,但了解到它不是那样工作的。您如何实现这种“动态”路由?

编辑: 所以在对代码进行了一些挖掘之后,我发现我必须实现自己的 DirectRouteProvider,有什么帮助吗?

【问题讨论】:

    标签: c# asp.net .net asp.net-mvc asp.net-web-api


    【解决方案1】:

    看来我刚刚解决了它.. 这是我的代码:

    public class CentralizedRouteProvider : DefaultDirectRouteProvider
    {
        protected override IReadOnlyList<RouteEntry> GetActionDirectRoutes(HttpActionDescriptor actionDescriptor,IReadOnlyList<IDirectRouteFactory> factories, IInlineConstraintResolver constraintResolver)
        {
            var result = base.GetActionDirectRoutes(actionDescriptor, factories, constraintResolver).ToList();
            var list = new List<RouteEntry>();
    
            foreach (var route in result.Where(r => r.Route.RouteTemplate.Contains("[ApiGroup]")))
            {
                var attribute = ((ReflectedHttpActionDescriptor)actionDescriptor).GetCustomAttributes<ApiGroupAttribute>().First();
    
                var newTemplate = route.Route.RouteTemplate.Replace("[ApiGroup]", attribute.GroupName);
    
                if (!result.Any(r => r.Route.RouteTemplate == newTemplate))
                {
                    var entry = new RouteEntry(null, new HttpRoute(newTemplate,
                        new HttpRouteValueDictionary(route.Route.Defaults),
                        new HttpRouteValueDictionary(route.Route.Constraints),
                        new HttpRouteValueDictionary(route.Route.DataTokens)));
                    list.Add(entry);
                }
            }
    
            return list.AsReadOnly();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-09-20
      • 1970-01-01
      • 1970-01-01
      • 2016-05-03
      • 1970-01-01
      • 1970-01-01
      • 2017-09-08
      • 1970-01-01
      • 2020-07-20
      相关资源
      最近更新 更多