Intercept all WebApi calls before the route matching occurs

前端 未结 4 838
青春惊慌失措
青春惊慌失措 2020-12-20 23:29

I am looking for a way to intercept/grab the request being made before matching to a route. For example, I have multiple controllers and routes set up, but I want some mecha

4条回答
  •  死守一世寂寞
    2020-12-20 23:42

    I'm using mentioned technique to log all requests and responses. Speaking shortly, the best way to do it is to use Handlers.

    First, create handler:

    public class CustomHandler : DelegatingHandler
    {
        protected override async Task SendAsync(
            HttpRequestMessage request, CancellationToken cancellationToken)
        {
            //get route values and process them
            var routeValues = (IHttpRouteData[]) HttpContext.Current.Request.RequestContext.RouteData.Values["MS_SubRoutes"];
    
            //let other handlers process the request
            return await base.SendAsync(request, cancellationToken)
                .ContinueWith(task =>
                {
                    //once response is ready, do something with it                                        
    
                    return task.Result;
                }, cancellationToken);
        }
    }
    

    Then, register it in WebApiConfig:

    config.MessageHandlers.Add(new CustomHandler());
    

提交回复
热议问题