ASP.NET Web Api Routing Customization

前端 未结 4 1689
刺人心
刺人心 2021-02-19 11:38

I have WebApi controllers that end with the \"Api\" suffix in their names (For ex: StudentsApiController, InstructorsApiController). I do this to easily differentiate my MVC con

4条回答
  •  青春惊慌失措
    2021-02-19 12:33

    Following @Youssef Moussaoui's direction I ended up writing the following code that solved the problem.

    public class ApiControllerSelector : DefaultHttpControllerSelector
    {
        public ApiControllerSelector(HttpConfiguration configuration)
            : base(configuration)
        {
        }
    
        public override string GetControllerName(HttpRequestMessage request)
        {
            if (request == null)
                throw new ArgumentNullException("request");
    
            IHttpRouteData routeData = request.GetRouteData();
    
            if (routeData == null)
                return null;
    
            // Look up controller in route data
            object controllerName;
            routeData.Values.TryGetValue("controller", out controllerName);
    
            if (controllerName != null)
                controllerName += "api";
    
            return (string)controllerName;
        }
    }
    

    And register it in Global.asax as

    GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpControllerSelector),
                new ApiControllerSelector(GlobalConfiguration.Configuration));
    

提交回复
热议问题