Asp.Net MVC 2.0 Filter基本用法

3次阅读

在这一节里,大家一同学习下 mvc 2.0 中的 filter, 简单的说,filter 就是标记在 action 上的一些属性,来实现对 action 的控制。      mvc2.0 中主要包括以下 filter
      1. Authorize
      2.HandleError
      3.RequireHttps
      4.OutputCache
          1. 首先说下 Authorize
          Authorize 主要用来实现用户的授权与访问。   

    [Authorize(Roles="Admins",Users="zx")]
        public ActionResult DellUser(string userName)
        {return View("about");
        }

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

   [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
     

         [OutputCache(Duration=60)]
        public ActionResult DellUser(string userName)
        {return View("about");
        }

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

      [RequireHttps]
        public ActionResult DellUser(string userName)
        {return View("about");
        }

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

正文完