36

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?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Darren
  • 497
  • 1
  • 4
  • 10

2 Answers2

66
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";
    }
}
Yang You
  • 2,618
  • 1
  • 25
  • 32
  • Thanks @yyou. What if I wanted to do this at the controller level? For example adding 2 [RoutePrefix] to the Controller class – Darren Dec 11 '15 at 00:39
  • 1
    thanks! noticed that there's no way to have more than one [RoutePrefix]. Found another workaround via http://stackoverflow.com/questions/24953660/asp-net-web-api-multiple-routeprefix. Your first solution works for my situation. :) – Darren Dec 11 '15 at 01:06
2
public class HomeController : Controller
{
[Route("")]
[Route("Home")]
[Route("Home/Index")]
[Route("Home/Index/{id?}")]
public IActionResult Index(int? id)
{
    return ControllerContext.MyDisplayRouteInfo(id);
}

[Route("Home/About")]
[Route("Home/About/{id?}")]
public IActionResult About(int? id)
{
    return ControllerContext.MyDisplayRouteInfo(id);
}
}

Or Read in Link https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/routing?view=aspnetcore-6.0

Amr Atef
  • 21
  • 3
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 01 '22 at 04:39