I am using web api with ASP.NET MVC 4.
I have the following named controller
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.