Routing in Web Api in ASP.NET MVC 4

孤街浪徒 提交于 2019-12-03 04:10:57

Well there are two issues in your code. You are using MapRoute instead of MapHttpRoute. You should also put the more detailed route first so it will not get swallowed by more generic one:

routes.MapHttpRoute(
    name: "Customer",
    url: "api/Customer/{id}",
    defaults: new { controller = "CustomerApi", action = "Get", id = UrlParameter.Optional }
); 

routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

Now if you want your solution to be more generic (when you have more controllers which need to be modified like this) you can use custom HttpControllerRouteHandler to transform incoming controllers names, this way you will be able to keep default routing.

First you need to create custom HttpControllerRouteHandler:

public class CustomHttpControllerRouteHandler : HttpControllerRouteHandler
{
    protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        requestContext.RouteData.Values["controller"] = requestContext.RouteData.Values["controller"].ToString() + "Api";

        return base.GetHttpHandler(requestContext);
    }
}

Now you can register your HttpRoute like this:

routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
).RouteHandler = new CustomHttpControllerRouteHandler();

This way when you put Customer into URL the engine will treat it like CustomerApi.

You could extend DefaultHttpControllerSelector and override GetControllerName to apply a custom rule. The default implementation just returns the value of the "controller" variable from the route data. A custom implementation could map this to some other value. See Routing and Action Selection.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!