Multiple routes assigned to one method, how to determine which route was called?
[HttpGet("api/route1")]
[HttpGet("api/route2")]
[HttpGet("api/route3")]
public void example ()
{
string requestedRoute = this.ControllerContext.HttpContext.Request.Path.ToString();
if(requestedRoute == "/api/route1"){
//do something
}
}
This works for me.
I wanted to be able to pass different views based on the request but they all basically used the same process and didn't want to make an action for each. The prior answer doesn't seem to work any more so here is what I came up with. This is .Net Core 2.2.
[HttpGet]
[Route("[controller]/ManageAccessView/{name}/{id}",Name = "ManageAccessView")]
[Route("[controller]/ManageAccessUsers/{name}/{id}", Name = "ManageAccessUsers")]
[Route("[controller]/ManageAccessKeys/{name}/{id}", Name = "ManageAccessKeys")]
public async Task<IActionResult> ManageAccessView(int id, string name)
{
var requestedView = this.ControllerContext.ActionDescriptor.AttributeRouteInfo.Name;
return View(requestedView);
}
This will allow you to put your individual views as the name of the routes and use them to set the view.
You can look at ControllerContext.RouteData
to figure out which route they used when using multiple routes for one action.
public const string MultiARoute = "multiA/{routesuffix}";
public const string MultiBRoute = "multiB/subB/{routesuffix}";
[Route(MultiARoute)]
[Route(MultiBRoute)]
public ActionResult MultiRoute(string routeSuffix)
{
var route = this.ControllerContext.RouteData.Route as Route;
string whatAmI = string.Empty;
if (route.Url == MultiARoute)
{
whatAmI = "A";
}
else
{
whatAmI = "B";
}
return View();
}