Action Filters以及自訂OutputCache ActionFilterAttribute事件發生次序

來源:互聯網
上載者:User

理解 Action Filters

Action filter 是能夠應用於 controller action --或整個controller的一個特性,它們的基類為System.Web.Mvc.FilterAttribute 。它限定了action執行的方式。ASP.NET MVC架構套件含數個action filters。

HandleError – 這個action 過濾器處理controller action執行時出現的錯誤。

OutputCache – 這個action 過濾器將 controller action的輸出緩衝一段制定的時間 .

Authorize – 這個action 過濾器使你能夠限制特定的使用者或角色的訪問.

使用Action Filter

action filter是一個特性. 你能夠應用大部分的action filters 在單個的controller action 或者整個controller上.

例如下面的Data controller有一個返回目前時間的Index()方法.這個action擁有OutputCache action filter. 這個過濾器導致由action返回的值能夠緩衝10秒鐘.

VaryByParam 屬性使用的設定不建議通過設定“*”的值來使用所有參數進行區分。這可能會導致緩衝溢出。

Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/    -->public class DataController : Controller    {        //        // GET: /Data/        [OutputCache(Duration = 20,VaryByParam ="")]        public string Index()        {            return DateTime.Now.ToString();        }    }

如果你重複調用Index() action(不斷重新整理當前頁面), 那麼你將看到當前的內容在Duration = 20秒內是不變的.

一個單一的action filter –  OutputCache action filter – 被應用於Index() 方法. 同樣,你可以應用多個action filters 在同一個action上.

不同類型的Filters

ASP.NET MVC架構支援多種不同類型的過濾器:

Authorization filters – 實現IAuthorizationFilter 特性.

Action filters – 實現IActionFilter 特性.

Result filters – 實現IResultFilter 特性.

Exception filters –實現IExceptionFilter 特性.

Filters 按照上面列出的順序執行。例如, authorization filters 總是在action filters之前執行,exception filters在所有其他類型的filter之後執行.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.