Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I log the raw HTTP request in ASP.NET Web API whether or not it routes to a controller?

Is it possible to log every HTTP request made to an ASP.NET Web API, even if the request is malformed, or for some other reason fails to route to one of the controllers.

For example, if a POST method has an Order model as it's parameter, an incorrect request will prevent it from ever reaching the controller's POST method. I'd like to alert someone so that actions can be taken to prevent future failures.

Is there a way to capture these requests further upstream from the controller?

like image 524
Feckmore Avatar asked Oct 19 '12 14:10

Feckmore


2 Answers

Either use Tracing, you need to implement ITraceWriter as shown below

http://www.asp.net/web-api/overview/testing-and-debugging/tracing-in-aspnet-web-api

Or implement message handlers

http://www.strathweb.com/2012/05/implementing-message-handlers-to-track-your-asp-net-web-api-usage/

http://www.asp.net/web-api/overview/working-with-http/http-message-handlers

Message handlers allow you to change message before it comes to HttpControllerDispatcher, and therefore you can handle common problems with routing and action method selection.

But as the last do not hesitate to use AppFabric logging, when you are hosting on IIS, because it can give you information when something is going wrong before requests come to your Web Application. It handles scenarions with global errors in web application, for example errors with web.config.

like image 144
Regfor Avatar answered Nov 10 '22 09:11

Regfor


If you enable tracing in the ASP.NET Web API per Tracing in ASP.NET Web API, the built-in tracing infrastructure will log the information you are after.

In the case of a malformed request that fails content negotiation, you will see an HttpError occur in the DefaultContentNegotiator.

Here is an example of the simple trace for this type of error:

DefaultContentNegotiator;Negotiate;Type='HttpError', formatters=[JsonMediaTypeFormatterTracer, XmlMediaTypeFormatterTracer, FormUrlEncodedMediaTypeFormatterTracer, FormUrlEncodedMediaTypeFormatterTracer]

The trace writer is given a TraceRecord as its input, which will contain the request information as well as optionally any custom information you might want to use.

The Web API will use the trace writer you configure to trace information throughout the lifecycle of requests. You can use trace writer to trace both the lifecycle events as well as your own controller code.

like image 30
Oppositional Avatar answered Nov 10 '22 10:11

Oppositional