WebApi message interception and webapi message interception
Recently, the company asked to monitor the server information (server information interception) of webapis. Since I have not done any convenient projects before, it is also difficult to do so, the process of exploration is also very painful, so we finally realized this function. So I will share this for everyone to learn from each other.
I personally think it is the simplest way to intercept webapi information. I am not very familiar with these services and have limited personal technologies, if you have any mistakes, you can give your comments.
First, create a class: MsgRecordFilterAttribute. This class inherits ActionFilterAttribute (this must reference System. Web. Http. Filters) and overwrites OnActionExecuting and OnActionExecuted methods.
The Code is as follows:
Public class MsgRecordFilterAttribute: ActionFilterAttribute
{
Public override void OnActionExecuting (System. Web. Http. Controllers. HttpActionContext actionContext)
{
Base. OnActionExecuting (actionContext );
}
Public override void OnActionExecuted (HttpActionExecutedContext actionExecutedContext)
{
Base. OnActionExecuted (actionExecutedContext );
}
}
This completes the interception class.
Step 2 Add a filter in the webapi WebApiConfig file:
Config. Filters. Add (new MsgRecordFilterAttribute ());
In this way, the WebApi information is intercepted: You can obtain the method name and return value of the method called by the client in method OnActionExecuting. In OnActionExecuted, you can obtain the returned results of a method. You can use these two methods to obtain the time spent calling the service.