Jun*_*ior 11 c# asp.net-core asp.net-core-routing asp.net-core-2.2
我有一个写在 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);
}
}
Run Code Online (Sandbox Code Playgroud)
如何在操作和/或视图中获取路线名称?
Dav*_*ong 12
对我来说,@krik-larkin 的答案不起作用,因为AttributeRouteInfo在我的情况下始终为空。
我用下面的代码代替:
var endpoint = HttpContext.GetEndpoint() as RouteEndpoint;
var routeNameMetadata = endpoint?.Metadata.OfType<RouteNameMetadata>().SingleOrDefault();
var routeName = routeNameMetadata?.RouteName;
Run Code Online (Sandbox Code Playgroud)
Kir*_*kin 11
内部控制器,你可以阅读AttributeRouteInfo从ControllerContext的ActionDescriptor。AttributeRouteInfo有一个Name属性,它保存您正在寻找的值:
public ActionResult Act(ActVM viewModel)
{
switch (ControllerContext.ActionDescriptor.AttributeRouteInfo.Name)
{
// ...
}
return View(viewModel);
}
Run Code Online (Sandbox Code Playgroud)
在 Razor 视图中,ActionDescriptor可通过ViewContext属性获得:
@{
var routeName = ViewContext.ActionDescriptor.AttributeRouteInfo.Name;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8458 次 |
| 最近记录: |