Asp.Net MVC 2.0 Filter基本用法

在这一节里,大家一同学习下mvc 2.0中的filter,简单的说,filter就是标记在action上的一些属性,来实现对action的控制。

   mvc2.0中主要包括以下filter

   1. Authorize

   2.HandleError

   3.RequireHttps

   4.OutputCache

       1. 首先说下Authorize

       Authorize主要用来实现用户的授权与访问。  

  1. [Authorize(Roles="Admins",Users="zx")] 
  2.        public ActionResult DellUser(string userName) 
  3.        { 
  4.            return View("about"); 
  5.        } 
 [Authorize(Roles="Admins",Users="zx")]
        public ActionResult DellUser(string userName)
        {
            return View("about");
        }

    上面的代码表明DellUser这个action只能被角色为admins下的zx用户访问,其他用户和角色均被禁止访问

   2.HandleError

     

  1. [HandleError(Order=1,ExceptionType=typeof(ArgumentException),View="Error")] 
  2.         [HandleError(Order=2,ExceptionType=typeof(Exception))] 
  3.         public ActionResult DellUser(string userName) 
  4.         { 
  5.             if (string.IsNullOrEmpty(userName)) 
  6.             { 
  7.                 thrownew ArgumentException(); 
  8.             } 
  9.             return View("about"); 
  10.         } 
[HandleError(Order=1,ExceptionType=typeof(ArgumentException),View="Error")]
        [HandleError(Order=2,ExceptionType=typeof(Exception))]
        public ActionResult DellUser(string userName)
        {
            if (string.IsNullOrEmpty(userName))
            {
                throw new ArgumentException();
            }
            return View("about");
        }

     HandleError用作异常处理,其中order表示处理异常的顺序,数字越小,优先级越高。

    ExceptionType表示异常类型

   View表示出现异常后转向的页面. 

   3.OutputCache

  

  1. [OutputCache(Duration=60)] 
  2.   public ActionResult DellUser(string userName) 
  3.   { 
  4.       return View("about"); 
  5.   } 
      [OutputCache(Duration=60)]
        public ActionResult DellUser(string userName)
        {
            return View("about");
        }

OutputCache用来表示页面缓存,在WEBFORM时代,在ASP.NET页面中可以直接设置这个属性,在MVC中直接在ACTION上标记属性。

   4. RequireHttps

   

  1. [RequireHttps] 
  2.      public ActionResult DellUser(string userName) 
  3.      { 
  4.          return View("about"); 
  5.      } 
   [RequireHttps]
        public ActionResult DellUser(string userName)
        {
            return View("about");
        }

  RequireHttps表示DellUser这个action只能使用https协议才能访问,使用其他协议不行。

原文地址:https://www.cnblogs.com/itjeff/p/3359474.html