junep
junep

Reputation: 2164

Using global variable in ASP.NET Core controller

The question is simple but I don't know how use it.

For example there is a controller

public class MainController : Controller
{
    private int a;

    public IActionResult Index(bool set = true)
    {
        if (set) a = 10;

        return View(a)
    }
}

If I get in Index page at first time, I set a = 10. And I get in Index page again (for example refresh Index page or paging in Index page, i.e. move in same page) Actually, I get in Index page with url : ~Index?set=False after first access.

Then the a has 0 (default for int variable). I did not know the Controller page (Controller class) is always initialized when I gen in it even when I move to same page.

So, I want to use variable like global variable not using session.

Is there any way?

Upvotes: 6

Views: 25019

Answers (1)

John Wu
John Wu

Reputation: 52250

It sounds like you wish to persist a variable between requests.

Per user

If you wish to store a variable that persists but is only visible to the current user, use session state:

public int? A
{
    get 
    {
        return HttpContext.Current.Session["A"] as int?;
    }
    set
    {
        HttpContext.Current.Session["A"] = value;
    }
}

Note that we are using int? instead of int in order to handle the case where the session variable has not yet been set. If you prefer to default to 0, you can simply use the coalesce operator, ??.

Truly global

If you wish to persist a variable in a manner where there is only one copy for all users, you can store it in a static variable or in an application state variable.

So either

static volatile public int a;

Or

public int? A
{
    get 
    {
        return HttpContext.Current.Application["A"] as int?;
    }
    set
    {
        HttpContext.Current.Application["A"] = value;
    }
}

Obviously variables that are shared between users can change at any time (due to activity in other threads), so you should be careful about how you handle them. For variables that are int-sized or smaller, the processor will perform atomic reads and writes, but for variables larger than an int you may need to use Interlocked or lock to control access.

You do not need to worry about thread synchronization for session variables; the framework handles it for you.

Note: The above is just an example to help you find the right API. It does not necessarily demonstrate the best pattern-- accessing HttpContext via the static method Current is considered bad form, as it makes it impossible to mock the context. Please see this article for ways to expose it to your code via DI.

Upvotes: 9

Related Questions