When I receive a Web API request, I want to create a variable that will be accessible by every class during the life-cycle of the request. I want it to be accessed like a static property in such a way as App.User
from any class. But I do not want it to be preserved after the processing of the request, so I guess SessionState is not an option. What would be the proper way to do this?
EDIT: It needs to be thread-safe,too.
As Igor notes, one option is to use dependency injection plus parameter passing to make your "global" variable accessible to everything that needs it.
But if you really want to use a static property, then you can use the HttpContext.Items property to stash temporary data pertaining to just the current request:
public class App
{
public static IUser User
{
get { return (IUser)HttpContext.Current.Items["User"]; }
set { HttpContext.Current.Items["User"] = value; }
}
}
A third option (which I don't recommend) is to use a static field backed by the ThreadStatic attribute:
public class App
{
[ThreadStatic]
private static IUser user;
public static IUser User
{
get { return user; }
set { user = value; }
}
}
This option has the advantage that it has no dependencies on System.Web. However, it is only valid if your controller is synchronous, and it will break if you ever use async
.
HttpContext.Items is intended specifically for this purpose.
Anything you put in there will exist for the lifespan of the current request, then be demolished afterward.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With