Introduction to Filter
Filter is often used in Web APIs, mainly for logging, security verification, global error handling, etc. the Web API provides the basic type of two types of filters: Actionfilterattribute,exceptionfilterattribute ; Two classes are abstract classes, actionfilter main implementations before executing the request method body (overriding the base class method OnActionExecuting), and subsequent event handling (overriding the base class method onactionexecuted) Exceptionfilter mainly implements the triggering exception method (overriding the base class method Onexception). Here is an example of the former type.
New Actionfilter Class
Print parameters, return values, and interface response time:
public class Actionfilter:actionfilterattribute {Private Const string Key = "action"; private bool _isdebuglog = true; public override void OnActionExecuting (Httpactioncontext actioncontext) {if (_isdebuglog) { Stopwatch Stopwatch = new Stopwatch (); Actioncontext.request.properties[key] = StopWatch; string actionname = ActionContext.ActionDescriptor.ActionName; Debug.Print (Newtonsoft.Json.JsonConvert.SerializeObject (actioncontext.actionarguments)); Stopwatch.start (); }} public override void OnActionExecuted (Httpactionexecutedcontext actionexecutedcontext) { if (_isdebuglog) {Stopwatch Stopwatch = Actionexecutedcontext.request.properties[key] as Sto Pwatch; if (StopWatch! = null) {stopwatch.stop (); String actionname = aCtionExecutedContext.ActionContext.ActionDescriptor.ActionName; string controllername = ActionExecutedContext.ActionContext.ActionDescriptor.ControllerDescriptor.ControllerName; Debug.Print (ActionExecutedContext.Response.Content.ReadAsStringAsync (). Result); Debug.Print (String. Format (@ "[{0}/{1} spents {2}ms]", Controllername, ActionName, stopWatch.Elapsed.TotalMilliseconds)); } } } }
Add a filter on the action method of an interface
[Actionfilter]
or add filters to the configuration, which would be equivalent to adding a filter on each interface
Demonstrate
Send request:
Interface response:
"C #" WebApi adds a filter that enables logging of request parameters and response content