Intercept all WebApi calls before the route matching occurs

前端 未结 4 820
青春惊慌失措
青春惊慌失措 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<HttpResponseMessage> 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());
    
    0 讨论(0)
  • 2020-12-20 23:51

    Like Joel Etherton mentioned in the comments, I think what you are looking for is something like adding the following code in your global.asax:

    protected void Application_EndRequest()
    {
        /*
        if(HttpContext.Current.Response.StatusCode == 404)
            Debug.WriteLine("404 something something")
        if(HttpContext.Current.Response.StatusCode == 500)
            Debug.WriteLine("500 something something")
        if(HttpContext.Current.Response.StatusCode == 200)
            Debug.WriteLine("200 something something")
        */
        Debug.WriteLine($"{context.Response.StatusCode} - {request.Url.PathAndQuery}");
    }
    

    I got my inspiration from here: ASP.NET MVC 404 Error Handling

    0 讨论(0)
  • 2020-12-20 23:55

    Would it work to create a HttpHandler (or do it just in Global asax Application_BeginRequest event) to capture the requests and inside the handler parse the URL against route config, similar to this link.

    0 讨论(0)
  • 2020-12-21 00:03

    What you need is action filters. You can apply action filters directly to controllers as attributes, the caveat with Action filters is that at this point the controller route is already known but you can still control (very much like AOP) if the action method can be executed or not:

    ASP.NET Web API ActionFilter example

    Look at how you can use an action filter, in this case for logging:

    public class LogActionFilter : ActionFilterAttribute 
    {
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            Log(actionExecutedContext.ActionContext.RequestContext.RouteData);
    
            base.OnActionExecuted(actionExecutedContext);
        }
    
        private void Log(System.Web.Http.Routing.IHttpRouteData httpRouteData)
        {
            var controllerName = "controller name";
            var actionName = "action name";
            var message = String.Format("controller:{0}, action:{1}", controllerName, actionName);
    
        Debug.WriteLine(message, "Action Filter Log");
        }
    }
    

    How to log which action method is executed in a controller in webapi

    You can also use message handlers, which are executed before the controller is resolved:

    HTTP Message Handlers in ASP.NET Web API

    0 讨论(0)
提交回复
热议问题