Web API Filter ActionFilterAttribute, webapiactionfilter
WebApi provides two filter types:
1. ActionFilterAttribute
2. predictionfilterattribute
The two classes are both abstract classes. ActionFilter mainly implements the processing of the following events before the request method body is executed (override the base class method: OnActionExecuting) (override the base class method: OnActionExecuted ). Predictionfilter mainly implements the exception method (override the base class method: OnException ).
Filters are frequently used in actual projects, such as logs, security verification, and global error handling.
Below is a small example:
1. CreateActionFilterAttribute:
Public class ActionFilter: ActionFilterAttribute {public override void OnActionExecuting (System. web. http. controllers. httpActionContext actionContext) {base. onActionExecuting (actionContext); // get the request message to extract data Stream = actionContext. request. content. readAsStreamAsync (). result; Encoding encoding = Encoding. UTF8; stream. position = 0; string responseData = ""; using (StreamReader reader = new StreamR Eader (stream, encoding) {responseData = reader. readToEnd (). toString () ;}// deserialization for processing var serialize = new JavaScriptSerializer (); var obj = serialize. deserialize <RequestDTO> (responseData); // when the request is terminated before the action is executed, the fill method Response should be used, and no action body will be returned. If (obj = null) actionContext. response = actionContext. request. createResponse (HttpStatusCode. OK, obj); if (string. isNullOrEmpty (obj. phoneType) | string. isNullOrEmpty (obj. phoneVersion) | string. isNullOrEmpty (obj. phoneID) | obj. startCity <1) {actionContext. response = actionContext. request. createResponse (HttpStatusCode. OK, obj );}}}View Code
2. Add the [Filter class] to the Action Method of the Api controller, for example, [Filter. ActionFilter].
Public class mobileappscontroller: ApiController {private doworkdeskinvoke _ DoWork = new doworkdeskinvoke (); [Uzai. mobile. filter. actionFilter] [HttpPost] public RepProductTopicsList getretries producttopicslist (ReqProductTopicsList reqDTO) {return _ DoWork. getretries producttopicslist (reqDTO );}}View Code
This article will be gradually improved in the future. There will be a lot of simple examples of WebApi on the Internet, but there are few in-depth design development and practical applications, and there are not many books in this regard, you can seek your own answers on MSDN.