Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>One way you could achieve this is to write a DelegatingHandler to intercept the response before it gets sent back to the client, and then log information on those requests that return errors.</p> <pre><code>public class RepsonseInterceptor : DelegatingHandler { protected async override Task&lt;HttpResponseMessage&gt; SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var response = await base.SendAsync(request, cancellationToken); LogResponse(request, response); return response; } public void LogResponse(HttpRequestMessage request, HttpResponseMessage response) { HttpStatusCode status = response.StatusCode; //Catch the status codes you want to Log if (status == HttpStatusCode.NotFound || status == HttpStatusCode.Unauthorized || status == HttpStatusCode.InternalServerError) { //Do Logging Stuff here //with the Request and Response } } } </code></pre> <p>Then add this to the Application_Start in the Global.asax.cs:</p> <pre><code>GlobalConfiguration.Configuration.MessageHandlers.Add(new ResponseInterceptor()); </code></pre> <p>EDIT:</p> <p>If you don't want to execute the handler for all routes you can add it as a Per-Route Message Handler to those routes you want instead of globally like so:</p> <pre><code>config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional }, constraints: null, handler: new ResponseInterceptor() ); </code></pre> <p>If you are using .NET Framework 4.0 you need to change the SendAsync method of the handler as follows:</p> <pre><code>protected override Task&lt;HttpResponseMessage&gt; SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { return base.SendAsync(request, cancellationToken) .ContinueWith(task =&gt; { var response = task.Result; LogResponse(request, response); return response; }); } </code></pre> <p>I think it would be reasonable to just use this MessageHandler if you can obtain all of the information that you need to log from the Request and Response objects, although I've not fully tested this out.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload