Code: Request Correlation in ASP.NET

I’ve been involving in some tracing work today where we wanted to make sure each request had a correlation id.

Rather than inventing our own number, I wanted to use the request id that IIS already uses internally. This allows us to correlate across even more log files.

Here’s the totally unintuitive code that you need to use to retrieve this value:

var serviceProvider = (IServiceProvider)HttpContext.Current;
var workerRequest = (HttpWorkerRequest)provider.GetService(typeof(HttpWorkerRequest));
var traceId = workerRequest.RequestTraceIdentifier;

(A major motivator for this post was to save me having to trawl back to my sent emails from 2009 the next time I need this code.)

Update 28th Feb 2013: Some people have been seeing Guid.Empty when querying this property. The trace identifier is only available if IIS’s ETW mechanism is enabled. See for details on how to enable IIS tracing. Thanks to Levi Broderick from the ASP.NET team for adding this.

5 thoughts on “Code: Request Correlation in ASP.NET

  1. Looks like a good thing to extend:

    public static class HttpContextExtensions
    public static Guid GetRequestTraceIdentifier(this HttpContext context)
    var provider = (IServiceProvider)HttpContext.Current;
    var workerRequest = (HttpWorkerRequest)provider.GetService(typeof(HttpWorkerRequest));
    return workerRequest.RequestTraceIdentifier;

  2. Interesting, is it because there’s something special you can do with that ID later? i.e. where does IIS use that trace identifier? Or was it purely to avoid inventing your own number?

Comments are closed.