title: Injecting request ID in Web API
body: <p>I want to maintain an ID (<code>Guid.NewGuid()</code> will suffice) throughout processing request so later I can check logs for a given ID. I'm also returning the ID to the caller in response headers (and messages) in case of an error, they have a reference.</p>
  
  <p>First I did this in the application's Global.asax <code>Application_BeginRequest()</code> method, where I put the ID in the <code>HttpContext.Current.Items</code> collection.</p>
  
  <pre><code>protected void Application_BeginRequest(object sender, EventArgs e)
  {
      var context = HttpContext.Current;
      if (context != null)
      {
          var reqguid = Guid.NewGuid().ToString("D");
          context.Items.Add("sessionid", reqguid);
      }
  }
  </code></pre>
  
  <p>This worked fine in previous applications, but I felt a bit iffy about using <code>HttpContext</code> in a "modern" Web API application.</p>
  
  <p>Then I turned to Action Filters, because apparently that's the bees knees for Web API</p>
  
  <pre><code>public class ManageRequestHeadersFilter : ActionFilterAttribute
  {
      public override void OnActionExecuting(HttpActionContext actionContext)
      {
          actionContext.Request.Properties.Add("sessionid", Guid.NewGuid().ToString("D"));
      }
  
      public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
      {
          var sessionId = actionExecutedContext.Request.Properties["sessionid"].ToString();
          if (sessionId != null)
          {
              actionExecutedContext.Response.Headers.Add("App-Session-Id", sessionId);
          }
      }
  }
  ...
  config.Filters.Add(new ManageRequestHeadersFilter());
  </code></pre>
  
  <p>This worked OK too, until I wanted to get to the <code>Request</code> object in the <code>ApiController</code> constructor to set a helper property to the ID. Since the controller constructor runs before the filter, the <code>Request</code> object is null. Again, I could probably use the <code>HttpContext.Current</code> way, but that beats the purpose of filters.</p>
  
  <p>I also thought of using dependency injection (already using Autofac) to inject the ID into the constructor, which again, worked, but now I'd be doing things a bit backwards which feels weird to my original train of thought.</p>
  
  <p>My feeling is that passing in the ID as a controller constructor parameter will ultimately be the winner, because when Unit Testing, I shouldn't be relying on anything HTTP anyway.</p>
  
  <p>Is there already a best practice for this?</p>