Search code examples
c#asp.net-web-apinloghttpcontext

Alternative to HttpContext.Current.Items in ASP.NET Web Api


is there a non- System.Web/HttpContext alternative to HttpContext.Current.Items, a per-request data storage?

I want to save information of a request, save them and read the values from my logger (NLog). I found a good place to do this is the DefaultHttpControllerActivator/IHttpControllerActivator.

This way the log messages should always look the same and the developer doesn't have much influence on the format or information provided.

Edit: After some more research i found this: How can we create a callcontext for async .net methods? I hope using the logical call context with immutable collections will work as expected.


Solution

  • HttpRequestMessage.Properties is an IDictionary<string, Object> collection for storing arbitrary per-request data. Within a controller action this is readily available as Request.Properties property on the base ApiController class.

    Not sure how exactly you're planning on using this for logging, but you may also want to look into writing a Logging DelegatingHandler