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.