WebApi2 attribute routing inherited controllers

梦想的初衷 提交于 2019-12-04 10:07:52
Nkosi

The answer you quoted has since been updated. As of WebApi 2.2 they created an extensibility point to allow the feature you wanted. Attribute rout can be inherited, but you need to configure it. I had the same requirement for a base API controller and after searching came across the same answer you quoted.

.NET WebAPI Attribute Routing and inheritance

You need to overwrite the DefaultDirectRoutePrivider:

public class WebApiCustomDirectRouteProvider : DefaultDirectRouteProvider {
    protected override System.Collections.Generic.IReadOnlyList<IDirectRouteFactory>
        GetActionRouteFactories(System.Web.Http.Controllers.HttpActionDescriptor actionDescriptor) {
        // inherit route attributes decorated on base class controller's actions
        return actionDescriptor.GetCustomAttributes<IDirectRouteFactory>(inherit: true);
    }
}

With that done you then need to configure it in your web api configuration

public static class WebApiConfig {
    public static void Register(HttpConfiguration config) {
        .....
        // Attribute routing. (with inheritance)
        config.MapHttpAttributeRoutes(new WebApiCustomDirectRouteProvider());
        ....
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!