Tatham Oddie

Code: Request Correlation in ASP.NET

with 5 comments

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 http://www.iis.net/configreference/system.webserver/httptracing for details on how to enable IIS tracing. Thanks to Levi Broderick from the ASP.NET team for adding this.

Written by Tatham Oddie

February 7, 2012 at 14:27

Posted in Uncategorized

5 Responses

Subscribe to comments with RSS.

  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;
    }
    }

    tsjensen

    February 7, 2012 at 15:33

  2. Is there something I need to do to IIS to enable this? I’m getting Guid.Empty backkk

    Harry McIntyre

    March 8, 2012 at 03:03

    • Hmm. Which version of IIS? Which version of ASP.NET? Integrated or classic mode?

      Tatham Oddie

      March 26, 2012 at 22:46

  3. 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?

    Dwain Bunker

    March 14, 2012 at 21:02


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 28 other followers

%d bloggers like this: