.NET MVC 获取路由模板
.NET MVC get route template
假设我有一个带有路由模板的控制器/users/{userId}/profilePhoto
假设一位用户访问了 /users/123/profilePhoto
,另一位用户访问了 /users/444/profilePhoto
。
有什么方法可以找到用于解决该请求的路由模板 (/users/{userId}/profilePhoto
)?例如,是否可以从 HttpContext
?
中读取它?
来自控制器操作方法:
((Route)RouteData.Route).Url
RouteData
is a property on the controller. It has a Route
property of type RouteBase
, which should be castable to Route
, which has a Url
property that contains the template.
从控制器操作方法外部,您做同样的事情,但首先您需要获取当前请求上下文:
((Route)HttpContext.Current.Request.RequestContext.RouteData.Route).Url;
要在操作方法中获取当前使用的路由,您可以简单地执行以下操作:
public ActionResult Index()
{
var route = this.RouteData.Route;
return View();
}
this
解析为当前控制器,可以省略。我只是把它留在里面以提醒自己当前的范围。
假设我有一个带有路由模板的控制器/users/{userId}/profilePhoto
假设一位用户访问了 /users/123/profilePhoto
,另一位用户访问了 /users/444/profilePhoto
。
有什么方法可以找到用于解决该请求的路由模板 (/users/{userId}/profilePhoto
)?例如,是否可以从 HttpContext
?
来自控制器操作方法:
((Route)RouteData.Route).Url
RouteData
is a property on the controller. It has a Route
property of type RouteBase
, which should be castable to Route
, which has a Url
property that contains the template.
从控制器操作方法外部,您做同样的事情,但首先您需要获取当前请求上下文:
((Route)HttpContext.Current.Request.RequestContext.RouteData.Route).Url;
要在操作方法中获取当前使用的路由,您可以简单地执行以下操作:
public ActionResult Index()
{
var route = this.RouteData.Route;
return View();
}
this
解析为当前控制器,可以省略。我只是把它留在里面以提醒自己当前的范围。