你可以申请在ASP.NET MVC的一个ActionFilter上的每一个动作 [英] Can you apply an ActionFilter in ASP.NET-MVC on EVERY action

查看:91
本文介绍了你可以申请在ASP.NET MVC的一个ActionFilter上的每一个动作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想申请的<一个href=\"http://weblogs.asp.net/rashid/archive/2008/03/28/asp-net-mvc-action-filter-caching-and-com$p$pssion.aspx\">ActionFilter在ASP.NET MVC中,以每一个动作我在我的应用程序 - 每个控制器上

I want to apply an ActionFilter in ASP.NET MVC to EVERY action I have in my application - on every controller.

有没有办法做到这一点,而不将其应用到每一个的ActionResult方法?

Is there a way to do this without applying it to every single ActionResult method ?

推荐答案

是的,你可以做到这一点,但它不是开箱的方式。我做了以下内容:

Yes, you can do this but it's not the way it works out of the box. I did the following:


  1. 创建一个基础类,并所有的控制器继承它

  2. 创建一个动作筛选器属性,并有从FilterAttribute和IActionFilter继承

  3. 用新的行动筛选器属性装饰你的基础类

这里的行动筛选器属性的样本:

Here's a sample of the action filter attribute:

public class SetCultureAttribute : FilterAttribute, IActionFilter 
{ 
    #region IActionFilter implementation

    public void OnActionExecuted(ActionExecutedContext filterContext)
    {
        //logic goes here
    }

    public void OnActionExecuting(ActionExecutingContext filterContext)
    {
        //or logic goes here
    }

    #endregion IActionFilter implementation
}

下面是具有这种属性的基础类的一个示例:

Here's a sample of the base controller class with this attribute:

[SetCulture]
public class ControllerBase : Controller
{
    ...
}

只要你的控制器类从ControllerBase那么SetCulture行动过滤器总是被执行继承使用此方法。我对这个一个完整样本,后在我的博客如果您想了解更多详细一点。

Using this method as long as your controller classes inherits from ControllerBase then the SetCulture action filter would always be executed. I have a full sample and post on this on my blog if you'd like a bit more detail.

希望帮助!

这篇关于你可以申请在ASP.NET MVC的一个ActionFilter上的每一个动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆