How to store global per request data in a .NET Web API project

Leslie Hanks picture Leslie Hanks · Sep 9, 2013 · Viewed 8k times · Source

I am working on writing a web api for my application that is currently written using ASP.NET Web Forms. I have a module that acquires some data at the beginning of the request and stores it in HttpContext.Current.Items so that it is available to all code later during the page processing.

I am trying to write my web api and it needs to do the same thing. What is the correct way to store "per request" global data to be used during processing for a web api controller (I suspect it would be the same for a regular controller as well).

Also, if there is a way to do so, is there a way to set this data in an IHttpModule that runs prior to the controller being instantiated.

Any help is appreciated!

Answer

Simon C picture Simon C · Sep 9, 2013

You can use the HttpRequestMessage.Properties dictionary as per this StackOverflow question.

There are other options like HttpContext or Session, but they can't be used in a self-hosting setup, only in WebHosting mode.