Web Api routing in ASP.NET MVC 4

I am using web api with ASP.NET MVC 4.

I have the following named controller

  • CustomerController: controller
  • CustomerApiController: ApiController

Previously, my CustomerApiController was named CustomersController , so to access it I just had to punch the following URL

local / api / clients

but now I have to save the name of the api controller as CustomerApiController . I want to be able to use the same method using localhost/api/Customers , what changes do I need to make?

I tried to make some changes to the RouteConfig.cs file. I tried adding the following to the RegisterRoutes method, but none of them worked.

 routes.MapHttpRoute( name: "API Default", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); routes.MapRoute( name: "Customers", url: "api/customer/", defaults: new { controller = "CustomerApi", action = "Get", id = UrlParameter.Optional } ); 

Please, can someone advise me about this. Thanks

+7
source share
2 answers

There are two problems in the code. You are using MapRoute instead of MapHttpRoute. You must first specify a more detailed route so that it does not swallow a more general route:

 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 general (when you have more controllers that need to be changed in this way), you can use the custom HttpControllerRouteHandler to translate the names of the incoming controllers, so you can support default routing.

First you need to create a 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 as follows:

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

That way, when you put the customer in the URL, the engine will treat it as CustomerApi.

+14
source

You can extend DefaultHttpControllerSelector and override GetControllerName to apply a special rule. The default implementation returns the value of the "controller" variable from the route data. A custom implementation may map this to a different value. See Routing and action selection .

0
source

All Articles