在带有Route属性的controller方法中获取控制器和动作名称
本文关键字:控制器 获取 方法 Route 属性 controller | 更新日期: 2023-09-27 18:06:44
我在控制器中定义了一个路由,
[Route("AboutUs/Profile")]
[Route("AboutUs/Organization")]
public ActionResult Contents()
{
string _controller = RouteData.Route.GetRouteData(this.HttpContext).Values["controller"].ToString();
string _action = RouteData.Route.GetRouteData(this.HttpContext).Values["action"].ToString();
}
但是_action == "Contents"
,我怎么得到_action = "Profile"
呢?
我试过了:
string _controller = this.ControllerContext.RouteData.Values["controller"].ToString();
string _action = this.ControllerContext.RouteData.Values["action"].ToString();
和
string _controller = this.RouteData.Values["controller"].ToString();
string _action = this.RouteData.Values["_action"].ToString();
但是这些都不起作用
我写了下面的代码来记录这些动作:
public class PreviousPage
{
public string Action { get; set; }
public string Controller { get; set; }
public object Parameters { get; set; }
public PreviousPage() { PP(); }
public PreviousPage(string action, string controller, object parameters)
{
Action = action;
Controller = controller;
Parameters = parameters;
}
public void PP()
{
var htpc = HttpContext.Current.Request.RequestContext.RouteData.Values;
object controller;
htpc.TryGetValue("controller", out controller);
Controller = controller as string;
object action;
htpc.TryGetValue("action", out action);
Action = action as string;
object id;
htpc.TryGetValue("id", out id);
int q = HttpContext.Current.Request.RawUrl.IndexOf('?');
if (q>-1)
Parameters = HttpContext.Current.Request.RawUrl.Substring(q+1);
else
Parameters = id as string;
}
}
这是不一致的,但稍加修改,你会达到的。
编辑:获取静态函数的动作:
public static string GetAction()
{
object action=null;
HttpContext.Current.Request.RequestContext.RouteData.Values.TryGetValue("action", out action);
return action as string;
}