ASP.NET MVC实践系列9-filter原理与实践


一、我们先来看看ASP.NET MVC 框架提供的几种默认filter类型:

  1、Authorize:

  准备工作:进入C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727文件夹,双击 aspnet_regsql.exe选择好相应的数据库,创建membership,AuthorizeAttribute使用membership来进行权限验证的,所以我们需要先在membership中准备一个用户lfm,一个角色Admin,我们使用studio的项目-》ASP.NET配置创建即可。

  [Authorize(Roles="Admin")]
        public ActionResult Index()
        {
            ViewData["Message"] = "Welcome to ASP.NET MVC!";
            return View();
        }

  如果lfm不属于Admin角色时Index页是不能访问的

  2、OutputCache:

 [OutputCache(Duration=60, VaryByParam="none")]
        public ActionResult About()
        {
            return View();
        }

  然后我们修改About加入:

 <%=DateTime.Now.ToString() %>

  我们会发现在一分钟内我们刷新About页面其输出并不改变。这个和webform中的页面缓存机制非常相似。

  这里我们也可以统一的配置时间和条件

  配置文件

    <system.web>
      <caching>
        <outputCacheSettings>
          <outputCacheProfiles>
            <add name="MyProfile" duration=”60” varyByParam=”none” />
          </outputCacheProfiles>
        </outputCacheSettings>
      </caching>
    </system.web>
Controler中输入

  [OutputCache(CacheProfile="MyProfile")]
        public ActionResult About()
        {
            return View();
        }

  3、Exception

       [HandleError(ExceptionType = typeof(ArgumentException), View = "Error")]
        public ActionResult GetProduct(string name)
        {
            if (name == null)
            {
                throw new ArgumentNullException("名字为空");
            }
            return View();
        }

  标明HandleError属性后的Action,当内部出现异常时会根据异常类型跳转到相应的View,这里需要注意的是上面的源码在开发期无法看到效果,必须部署到iis上才能看到效果。实际上这个简单处理在项目中用处不大,一般我们都会写自己的异常处理方式,自定义异常处理我们一会再自定义 filter中讲解。

  二、自定义filter实例:

  我们先来看一下跟filter相关的类结构:

一般情况下我们自定义的filter都是继承FilterAttribute类然后再扩展相应的接口的,下面我们举几个例子:

  1、自定义异常处理

  自定义异常处理

 1 public class ExceptionFilter : FilterAttribute,IExceptionFilter
 2     {
 3         void IExceptionFilter.OnException(ExceptionContext filterContext)
 4         {
 5             filterContext.Controller.ViewData["ErrorMessage"] = filterContext.Exception.Message;
 6             filterContext.Result = new ViewResult()
 7             {
 8                 ViewName = "Error",
 9                 ViewData = filterContext.Controller.ViewData,
10             };
11             filterContext.ExceptionHandled = true;
12         }

  使用

  Controller

  [ExceptionFilter]
        public ActionResult GetView(string name)
        {
            if (name == null)
            {
                throw new ArgumentNullException("名字为空");
            }
            return View();
        }

  浏览器中输入:http://localhost:3983/Home/GetView

  这样我们就可以根据自己的项目情况来处理异常了
2、监控Action运行时间的Timer

  TimerAttribute

 1 using System.Diagnostics;
 2 using System.Web.Mvc;
 3 public class TimerAttribute : ActionFilterAttribute
 4 {
 5     public TimerAttribute()
 6     {
 7         //By default, we should be the last filter to run
 8         //so we run just before and after the action method.
 9         this.Order = int.MaxValue;
10     }
11     public override void OnActionExecuting(ActionExecutingContext filterContext)
12     {
13         var controller = filterContext.Controller;
14         if (controller != null)
15         {
16             var stopwatch = new Stopwatch();
17             controller.ViewData["__StopWatch"] = stopwatch;
18             stopwatch.Start();
19         }
20     }
21     public override void OnActionExecuted(ActionExecutedContext filterContext)
22     {
23         var controller = filterContext.Controller;
24         if (controller != null)
25         {
26             var stopwatch = (Stopwatch)controller.ViewData["__StopWatch"];
27             stopwatch.Stop();
28             controller.ViewData["__Duration"] = stopwatch.Elapsed.TotalMilliseconds;
29         }
30     }
31 }


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3