ASP.NET Web API - requesting a specific global variable

When I receive a web API request, I want to create a variable that will be available to each class during the life of the request. I want it to be accessed as a static property in the same way as App.Userfrom any class. But I do not want it to persist after processing the request, so I believe that SessionState is not an option. What would be the right way to do this?

EDIT: It should also be thread safe.

+4
source share
2 answers

As Igor notes , one option is to use dependency forwarding plus parameter passing, so that your global variable is available for everything that needs it.

But if you really want to use the static property, you can use the HttpContext.Items property to store temporary data related to the simple current request:

public class App
{
    public static IUser User
    {
        get { return (IUser)HttpContext.Current.Items["User"]; }
        set { HttpContext.Current.Items["User"] = value; }
    }
}

The third option (which I do not recommend) is to use a static field supported 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 it async.

+3
0

Source: https://habr.com/ru/post/1664463/


All Articles