MVC专题 专题
您的位置:csharp > MVC专题专题 > ASP.Net MVC过滤器
ASP.Net MVC过滤器
作者:Aliot    发布时间:2019-11-19

在asp.net mvc中,控制器定义的操作方法通常与可能的用户交互具有一对一的关系,但有时候您希望在调用操作方法之前或者在操作方法运行之后执行逻辑。

为了支持这个功能,asp.net mvc提供了过滤器。 过滤器是一个自定义类,它提供了一种声明式和程序式的方法,可将操作前和操作后行为添加到控制器操作方法中。

动作过滤器

动作过滤器是一个属性,可以将其应用于控制器动作或整个控制器,以修改执行动作的方式。 asp.net mvc框架包含几个操作过滤器 -

  • outputcache - 将控制器操作的输出缓存指定的时间量。
  • handleerror - 处理执行控制器操作时引发的错误。
  • authorize - 使能够限制对特定用户或角色的访问。

过滤器的类型

asp.net mvc框架支持四种不同类型的过滤器 -

  • 授权过滤器 - 实现iauthorizationfilter属性。
  • 动作过滤器 - 实现iactionfilter属性。
  • 结果过滤器 - 实现iresultfilter属性。
  • 异常过滤器 - 实现iexceptionfilter属性。

过滤器按上面列出的顺序执行。例如,授权过滤器始终在每个其他类型的过滤器之后执行操作过滤器和异常过滤器之前执行。

授权过滤器 用于实现控制器操作的身份验证和授权。 例如,授权过滤器是授权过滤器的一个例子。

下面来看一个简单的例子,创建一个新的asp.net mvc项目。打开visual studio,然后单击菜单:文件 -> 新建 -> 项目 选项。创建一个名称为:mvcfiltersdemo 的mvc项目。

通过在解决方案资源管理器 中右键单击 controllers 文件夹来添加一个控件器:homecontroller。在弹出菜单项中选择:添加 -> 控制器

应用操作筛选器

动作过滤器可以应用于单独的控制器动作或整个控制器。 例如,操作筛选器outputcache应用于名为index()的操作,该操作返回字符串。 此过滤器会将该操作返回的值缓存15秒。

为了使这个实现这个例子,让我们修改控制器类通过改变称为index操作方法使用下面的代码 -

using system;
using system.collections.generic;
using system.linq;
using system.web;
using system.web.mvc;

namespace mvcfiltersdemo.controllers
{
    public class homecontroller : controller
    {
        // get: home
        // get: home
        [outputcache(duration = 15)]
        public string index()
        {
            return "this is asp.net mvc filters tutorial";
        }
    }
}

运行此应用程序时,将看到浏览器正在显示index操作方法的结果,如下所示 -

再添加另一个操作方法,它用于显示当前时间 -

using system;
using system.collections.generic;
using system.linq;
using system.web;
using system.web.mvc;

namespace mvcfiltersdemo.controllers
{
    public class homecontroller : controller
    {
        // get: home
        [outputcache(duration = 15)]
        public string index()
        {
            return "this is asp.net mvc filters tutorial";
        }
        // 返回当前时间
        [outputcache(duration = 20)]
        public string getcurrenttime()
        {
            return datetime.now.tostring("yyyy-mm-dd hh:mm:ss");
        }
    }
}

请求以下url:http://localhost:54713/home/getcurrenttime,将收到以下输出 -

如果刷新浏览器,则会看到相同的时间,因为该操作被缓存了20秒。20秒后刷新它将被更新。

自定义过滤器

要创建自己的自定义过滤器,asp.net mvc框架提供了一个叫作actionfilterattribute的基类。 这个类实现了iactionfilter和iresultfilter接口,都是从filter类派生的。

下面来看看看自定义过滤器的一个简单的例子,通过在项目中创建一个新的文件夹:actionfilters 。添加一个类,右键单击actionfilters 文件夹并选择:添加 ->

在类名称字段中输入mylogactionfilter,然后单击“添加” 按钮。

这个类将从actionfilterattribute派生,它是一个基类,并覆盖下面的方法。 以下是mylogactionfilter的完整实现。

using system;
using system.collections.generic;
using system.diagnostics;
using system.linq;

using system.web;
using system.web.mvc;
using system.web.routing;

namespace mvcfiltersdemo.actionfilters
{
    public class mylogactionfilter: actionfilterattribute
    {        

        public override void onactionexecuted(actionexecutedcontext filtercontext)
        {
            log("##########onactionexecuted", filtercontext.routedata);
        }

        public override void onresultexecuting(resultexecutingcontext filtercontext)
        {
            log("##########onresultexecuting", filtercontext.routedata);
        }

        public override void onresultexecuted(resultexecutedcontext filtercontext)
        {
            log("##########onresultexecuted", filtercontext.routedata);
        }

        private void log(string methodname, routedata routedata)
        {
            var controllername = routedata.values["controller"];
            var actionname = routedata.values["action"];

            var message = string.format(
               "{0} controller:{1} action:{2}", methodname, controllername, actionname);
            system.console.writeline("############################# yes ##################");
            debug.writeline(message, "action filter log");
        }
    }

}

现在,使用以下代码将日志过滤器应用于homecontroller控制器。

using mvcfiltersdemo.actionfilters;
using system;
using system.collections.generic;
using system.linq;
using system.web;
using system.web.mvc;

namespace mvcfiltersdemo.controllers
{
    [mylogactionfilter]
    public class homecontroller : controller
    {
        // get: home
        [outputcache(duration = 10)]
        public string index()
        {
            return "this is asp.net mvc filters tutorial";
        }

        // 返回当前时间
        [outputcache(duration = 10)]
        public string getcurrenttime()
        {
            return datetime.now.tostring("yyyy-mm-dd hh:mm:ss");
        }
    }
}

打开项目中的app_start,打开文件filterconfig.cs ,添加以下代码注册过滤器:mylogactionfilter -

using mvcfiltersdemo.actionfilters;
using system.web;
using system.web.mvc;

namespace mvcfiltersdemo
{
    public class filterconfig
    {
        public static void registerglobalfilters(globalfiltercollection filters)
        {
            filters.add(new handleerrorattribute());
            // 注册自定义action过滤器:优先级最低,但是可以作用到所有的控制器和action  
            filters.add(new mylogactionfilter());
        }
    }
}

运行应用程序,然后观察输出窗口。应该会看到类似(输出的最后几行)的结果 -

如上图所示,处理动作的每个阶段都有被记录到visual studio输出窗口中了。


网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册