![](/img/trans.png)
[英]How can I get the base route while doing service configuration in ASP.NET Core?
[英]How can I get the current route name with ASP.NET Core?
我有一個寫在 ASP.NET Core 2.2 框架之上的應用程序。
我有以下控制器
public class TestController : Controller
{
[Route("some-parameter-3/{name}/{id:int}/{page:int?}", Name = "SomeRoute3Name")]
[Route("some-parameter-2/{name}/{id:int}/{page:int?}", Name = "SomeRoute2Name")]
[Route("some-parameter-1/{name}/{id:int}/{page:int?}", Name = "SomeRoute1Name")]
public ActionResult Act(ActVM viewModel)
{
// switch the logic based on the route name
return View(viewModel);
}
}
如何在操作和/或視圖中獲取路線名稱?
在控制器內部,您可以從ControllerContext
的ActionDescriptor
讀取AttributeRouteInfo
。 AttributeRouteInfo
有一個Name
屬性,它保存您要查找的值:
public ActionResult Act(ActVM viewModel)
{
switch (ControllerContext.ActionDescriptor.AttributeRouteInfo.Name)
{
// ...
}
return View(viewModel);
}
在 Razor 視圖內部, ActionDescriptor
可通過ViewContext
屬性獲得:
@{
var routeName = ViewContext.ActionDescriptor.AttributeRouteInfo.Name;
}
對我來說,@krik-larkin 的答案不起作用,因為在我的情況下AttributeRouteInfo
始終為 null。
我改用以下代碼:
var endpoint = HttpContext.GetEndpoint() as RouteEndpoint;
var routeNameMetadata = endpoint?.Metadata.OfType<RouteNameMetadata>().SingleOrDefault();
var routeName = routeNameMetadata?.RouteName;
您還應該能夠查看具有路徑段,完整URL等的http請求對象的Context。
對 Kirk Larkin 回答的小修正。 有時您必須使用模板屬性而不是名稱:
var ari = ControllerContext.ActionDescriptor.AttributeRouteInfo;
var route = ari.Name ?? ari.Template;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.