Multiple routes assigned to one method, how to determine which route was called?

99封情书 提交于 2019-12-01 05:14:14

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();
}

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!