asp.net-mvc - 如何将变量传递给 ASP.NET MVC 应用程序中的自定义 ActionFilter

标签 asp.net-mvc asp.net-mvc-3 asp.net-mvc-4

我的 MVC 应用程序中有一个 Controller ,我尝试使用 onResultExecuted 方法使用自定义 ActionFilterAttribute 记录详细信息。

I read this tutorial 理解和编写我自己的 Action 过滤器。问题是如何将变量从 Controller 传递到 Action 过滤器?

  • 我想获取调用 Controller 的输入变量。比如说,用户名/用户 ID。
  • 如果(在某些情况下)任何 Controller 方法抛出异常,我也想记录错误。

  • Controller ——
    [MyActionFilter]
    public class myController : ApiController {
        public string Get(string x, int y) { .. }
        public string somemethod { .. }
    }
    

    Action 过滤器 -
    public class MyActionFilterAttribute : ActionFilterAttribute {
        public override void onActionExecuted(HttpActionExecutedContext actionExecutedContext) {
            // HOW DO I ACCESS THE VARIABLES OF THE CONTROLLER HERE
            // I NEED TO LOG THE EXCEPTIONS AND THE PARAMETERS PASSED TO THE CONTROLLER METHOD
        }
    }
    

    我希望我已经在这里解释了这个问题。抱歉,如果我在这里遗漏了一些基本对象,我对此完全陌生。

    最佳答案

    方法 - 1

    Action 过滤器

    public class MyActionFilter : ActionFilterAttribute
    {
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            base.OnActionExecuted(filterContext);
        }
    }
    

    操作方法
    [MyActionFilter]
    public ActionResult Index()
    {
        ViewBag.ControllerVariable = "12";
        return View();
    }
    

    enter image description here

    如果你注意截图,你可以看到ViewBag信息

    方法 - 2

    Action 过滤器
    public class MyActionFilter : ActionFilterAttribute
    {
        //Your Properties in Action Filter
        public string Property1 { get; set; }
        public string Property2 { get; set; }
    
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
        }
    }
    

    操作方法
    [MyActionFilter(Property1 = "Value1", Property2 = "Value2")]
    public ActionResult Index()
    {
        return View();
    }
    

    关于asp.net-mvc - 如何将变量传递给 ASP.NET MVC 应用程序中的自定义 ActionFilter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18209735/

    相关文章:

    javascript - 从 javascript 访问模型属性

    c# - Request.ServerVariables 抛出 NullReferenceException

    c# - 带有 Npgsql 的 Entity Framework 6

    json - ASP.NET MVC 4 JSON 绑定(bind)到 View 模型 - 嵌套对象错误

    javascript - 如何使用JS/jQuery在一个页面的两个局部 View 之间切换?

    asp.net-mvc - ASP.NET MVC URL 路由没有给我漂亮的 URL

    c# - MongoDB 引用的最佳实践

    c# - 对象中的值被清除

    asp.net-mvc - 为什么 View 知道模型?

    asp.net-mvc-4 - 如何通过 IP/角色/用户保护整个 MVC 区域?