Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Routes on a Controller

Was wondering if it was possible to have more than one route pointing to a WebApi controller?

For example I will like to have both http://domain/calculate and http://domain/v2/calculate pointing to the same controller function?

like image 242
Darren Avatar asked Dec 10 '15 23:12

Darren


People also ask

Can a controller have multiple get methods?

As mentioned, Web API controller can include multiple Get methods with different parameters and types.

Can we have multiple routes in MVC?

Multiple Routes You need to provide at least two parameters in MapRoute, route name, and URL pattern. The Defaults parameter is optional. You can register multiple custom routes with different names.

Can we map multiple URLs to the same action?

Yes, We can use multiple URLs to the same action with the use of a routing table. foreach(string url in urls)routes. MapRoute("RouteName-" + url, url, new { controller = "Page", action = "Index" });

What is a route controller?

The Route Controller is responsible for the preparation of the daily Delivery plan, monitoring the progress of Deliveries,Communicating the Route revisions to the Customer as well as the events that will have an impact on the Customers delivery.


1 Answers

public static class WebApiConfig     {         public static void Register(HttpConfiguration config)         {             // Web API configuration and services             // Configure Web API to use only bearer token authentication.             config.SuppressDefaultHostAuthentication();             config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));              // Web API routes             config.MapHttpAttributeRoutes();              config.Routes.MapHttpRoute(                 name: "route1",                 routeTemplate: "calculate",                 defaults: new { controller = "Calculator", action = "Get" });              config.Routes.MapHttpRoute(                 name: "route2",                 routeTemplate: "v2/calculate",                 defaults: new { controller = "Calculator", action = "Get" });              config.Routes.MapHttpRoute(                 name: "DefaultApi",                 routeTemplate: "api/{controller}/{id}",                 defaults: new { id = RouteParameter.Optional }             );         }     } 

OR

public class CalculatorController: ApiController {     [Route("calculate")]     [Route("v2/calculate")]     public String Get() {         return "xxxx";     } } 
like image 141
Yang You Avatar answered Sep 26 '22 21:09

Yang You