MVC应用程序自定义ActionFilter

MVC应用程序自定义ActionFilter

本文介绍了如何传递变量在ASP.NET MVC应用程序自定义ActionFilter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的MVC应用程序控制器为此我想使用自定义ActionFilterAttribute登录的详细信息,通过onResultExecuted方法。

I have a controller in my MVC app for which I'm trying to log details using a custom ActionFilterAttribute, by using the onResultExecuted method.

I阅读本教程 以理解和写我自己的行为过滤器。现在的问题是如何传递变量从控制器的动作过滤器?

I read this tutorial to understand and write my own action filter. The question is how do I pass variables from the controller to the action filter?


  1. 我想要得到与控制器被称为输入变量。比方说,用户名/用户ID。

  2. 如果(在某些情况下)异常是由任何控制器方法抛出,我要记录的错误了。

控制器 -

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

行动过滤器 -

The action filter -

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
    }
}

我希望我在这里说明了问题。道歉,如果我在这里错过了一些基本的对象,我完全新本。

I hope I have explained the problem here. Apologies if I'm missing out some basic objects here, I'm totally new to this.

推荐答案

行动过滤器

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

动作方法

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

如果你留意的截图中,可以看到 ViewBag 信息

If you pay attention to the screenshot, you can see the ViewBag information

行动过滤器

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应用程序自定义ActionFilter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 17:29