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

div*_*shm 21 asp.net-mvc asp.net-mvc-3 asp.net-mvc-4

我在我的MVC应用程序中有一个控制器,我正在尝试使用自定义ActionFilterAttribute来记录详细信息,方法是使用onResultExecuted方法.

我阅读本教程以了解并编写自己的动作过滤器.问题是如何将变量从控制器传递给动作过滤器?

  1. 我想获得调用控制器的输入变量.比如说,用户名/用户ID.
  2. 如果(在某些情况下)任何控制器方法抛出异常,我也想记录错误.

控制器 -

[MyActionFilter]
public class myController : ApiController {
    public string Get(string x, int y) { .. }
    public string somemethod { .. }
}
Run Code Online (Sandbox Code Playgroud)

动作过滤器 -

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
    }
}
Run Code Online (Sandbox Code Playgroud)

我希望我在这里解释了这个问题.抱歉,如果我在这里错过了一些基本的物体,我对此完全陌生.

Ima*_*ani 69

方法 - 1

动作过滤器

public class MyActionFilter : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        base.OnActionExecuted(filterContext);
    }
}
Run Code Online (Sandbox Code Playgroud)

行动方法

[MyActionFilter]
public ActionResult Index()
{
    ViewBag.ControllerVariable = "12";
    return View();
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

如果您注意截图,则可以查看ViewBag信息

方法 - 2

动作过滤器

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

行动方法

[MyActionFilter(Property1 = "Value1", Property2 = "Value2")]
public ActionResult Index()
{
    return View();
}
Run Code Online (Sandbox Code Playgroud)