【问题标题】:Get Action name from URL inside ActionFilterAttribute从 ActionFilterAttribute 中的 URL 获取操作名称
【发布时间】:2016-03-01 06:37:08
【问题描述】:

我正在编写从ASP.Net MVC 中的ActionFilterAttribute 类继承的自定义过滤器属性。我想从 url 获取动作名称,我试过了

ControllerContext controllerContext = new ControllerContext();
controllerContext.RouteData.Values["action"].ToString();

controllerContext.RouteData.Values 中没有项目,因此给了我空引用错误。有没有其他方法可以达到同样的效果?

【问题讨论】:

  • 您创建了一个 new 控制器上下文。在OnActionExecuting 方法中使用string actionName = (string)filterContext.RouteData.Values["action"];

标签: asp.net asp.net-mvc custom-action-filter


【解决方案1】:

试试下面的

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {

        string action = filterContext.ActionDescriptor.ActionName;
        string controller = filterContext.Controller.GetType().Name;

    }

【讨论】:

  • 虽然在你发帖之前我有一个答案,但你的答案看起来更好、更干净、更简单,而且只有一条线 :)
  • 嗨,如果可能的话,你能回答我在 asp mvc 缓存中面临的问题吗,here 是问题所在。任何帮助都会很棒。
【解决方案2】:
var rd = System.Web.HttpContext.Current.Request.RequestContext.RouteData;
string actionName = rd.GetRequiredString("action");

为我工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多