ASP.NET Web API - Filters
Filters : inject some logic into the request pipeline
- Authentication
- Authorization
- Action
- Result
- Exception
每一個 filter 在 pipeline 的執行順序都不一樣, 第一種叫做 AuthenticationFilters, 這個會根據 cookie verify your identity, 第二種是 AuthorazitaionFilters, 是用來掌管 what to do, 第三種是 ActionFilters, Action前後都可以使用, 第四種是 ResultFilters, 當前面的 ActionFilters 結束時, 可能會 return 一個 View, 假設你想要 parse html 做最後的處理, 可以render view 之前用這一個 ResultFilters, 最後是 ExceptionFilters, 處理 Exceptions
- Exception Filters
用來 handle exceptions 的 Filters
這裡舉一個例子, 在 update 我們的資料庫之前, 必須先檢查我們要 insert 的資料裡面有沒有 unique 的 constraint, 如果這個時候 table 有 unique constraint, 但是我們又輸入一樣的資料, 這個就會造成 Exception, 所以我們可以寫一個 DbUpdateExceptionFilterAttribute, 這一個 filter 會繼承 ExceptionFilterAttribute 這一個 base class
如果要用在 Controller, 可以在 method 上面加上 Attribute 就可以了
留言
張貼留言