Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Web API - Request Specific Global Variable [closed]

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.

like image 746
John L. Avatar asked Dec 21 '16 16:12

John L.


Video Answer


2 Answers

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.

like image 80
Michael Liu Avatar answered Oct 22 '22 08:10

Michael Liu


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.

like image 2
John Wu Avatar answered Oct 22 '22 09:10

John Wu