How do you inherit route prefixes at the controller class level in WebApi?

后端 未结 5 1421
粉色の甜心
粉色の甜心 2021-01-11 10:49

Note, I\'ve read about the new routing features as part of WebApi 2.2 to allow for inheritance of routes. This does not seem to solve my particular issue, however. It seems

5条回答
  •  独厮守ぢ
    2021-01-11 11:29

    Tried this in ASP.NET Web Api 2.2 (should/might also work in MVC):

    public class InheritedRoutePrefixDirectRouteProvider : DefaultDirectRouteProvider
    {
        protected override string GetRoutePrefix(HttpControllerDescriptor controllerDescriptor)
        {
            var sb = new StringBuilder(base.GetRoutePrefix(controllerDescriptor));
            var baseType = controllerDescriptor.ControllerType.BaseType;
    
            for (var t = baseType; typeof(ApiController).IsAssignableFrom(t); t = t.BaseType)
            {
                var a = (t as MemberInfo).GetCustomAttribute(false);
                if (a != null)
                {
                    sb.Insert(0, $"{a.Prefix}{(sb.Length > 0 ? "/": "")}");
                }
            }
    
            return sb.ToString();
        }
    }
    

    It links the route prefixes together in the controller inheritance chain.

提交回复
热议问题