2013年6月6日 星期四

[Asp.net MVC] Action Filter


在ASP.net MVC 中有以下幾種預設 filters providers :
過濾器類型 中文名稱 介面 實作
Authorization Filters 授權過濾器 IAuthorizationFilter AuthorizeAttribute
ChildActionOnlyAttribute
RequireHttpsAttribute
ValidateAntiForgeryTokenAttribute
ValidateInputAttribute
Action Filters 動作過濾器 IActionFilter ActionFilterAttribute
OutputCacheAttribute
AsyncTimeoutAttribute
Result Filters 結果過濾器 IResultFilter ActionFilterAttribute
Exception Filters 例外過濾器 IExceptionFilter HandleErrorAttribute
OutputCacheAttribute

執行順序 :
action filter life cycle
                                                       (圖片引用自http://www.dotnetexpertguide.com)


原文說明 :
  • Authorization filter, which makes security decisions about whether to execute an action method, such as performing authentication or validating properties of the request.
  • Action filter, which wraps the action method execution. This filter can perform additional processing, such as providing extra data to the action method, inspecting the return value, or canceling execution of the action method
  • Result filter, which wraps execution of the ActionResult object. This filter can perform additional processing of the result, such as modifying the HTTP response.
  • Exception filter, which executes if there is an unhandled exception thrown somewhere in action method, starting with the authorization filters and ending with the execution of the result. Exception filters can be used for tasks such as logging or displaying an error page.

ASP.NET MVC 目前內建的幾種 Filter :
  • [Authorize] 與Membership or FormsAuthentication 配合使用,驗證使用者是否有被授權執行Action,若驗證失敗會轉向預設登入頁面。
  • [AllowAnonymous] 套用此屬用,將會使此Action不被 Authorize 所作用,可不接受驗證授權即執行Action。
  • [ChildActionOnly] 套用此屬性之後,該Action 將只可透過 Html.RenderAction 執行,不可由外部URL 或是 RedirectToAction 所執行。
  • [RequireHttps] 僅可透過Https安全連線存取,若透過一般Http做存取,將會自動導向Https。
  • [ValidateInput] ASP.NET MVC 預設會將所有透過Form來的輸入資料作驗證,檢查是否有惡意的標籤或是程式碼,因此若要取得使用者所輸入的HTML標籤或是JS,就必須將此屬性設定為False。
  • [ValidateAntiForgeryToken] 在ASP.NET MVC 4 所新增的屬性,用以防止CSRF攻擊,使用時除了必須在Action套用此屬性之外,在View頁面的 Form表單中,必須在Sumbit之前插入 @Html.AntiForgeryTolen( ),否則會引發 『需要的反仿冒 Cookie "__RequestVerificationToken" 不存在 』的錯誤。
  • [AsyncTimeOut] 設定執行非同步控制時的 TimeOut 時間(毫秒),這邊須注意此屬性僅在 Controller 繼承 AsyncController 時,才有作用。
  • [NoAsyncTimeOut] 設定執行非同步控制時,不會有TimeOut時間,會不斷等待直到執行完畢為止,也一樣必須繼承AsyncController時,才有作用。
  • [OutputCache] 套用此屬性,可設定瀏覽器快取的相關設定。
  • [HandleError] 套用此屬性之後,不管是在Action執行階段,或者Result時發生錯誤,皆會觸發HandleError.OnException,若沒特別指定錯誤事件和指定的View,預設會將頁面導向預設的 /View/Shared/Error.cshtml。

Filter 作用域 :
1.僅套用於單一Action
    
    [HandleError]  //加在Action 之上
    public ActionResult Contact()
    {
        ViewBag.Message = "Your contact page.";
        return View();
    }

2.套用整個Controller
    
    [HandleError] //套用整個Controller
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
            return View();
        }
    }

3.註冊為全域(套用整個Asp.net MVC 專案)
    
//在App_Start中的FilterConfig中註冊filter
    public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }
    }





參考資訊

msdn--Filtering in ASP.NET MVC

asp.net mvc 官網教學 Home/MVC/Tutorials/Chapter 11. Hands On Labs/ASP.NET MVC 4 Custom Action Filters

沒有留言:

張貼留言