80

How do you declare global variables in ASP.NET MVC?

2
  • 1
    Your answer is - [MVC - How to declare global variables ](stackoverflow.com/questions/4171089/…) - Global variables in ASP.NET MVC Commented Feb 25, 2011 at 14:53
  • @SLaks It's very usefull when you want to create a quick and dirty prototype for a client. Poor designs and bad practices don't matter at all when you are making throw-away presale UI demo. Commented Mar 13, 2016 at 8:46

6 Answers 6

82

Technically any static variable or Property on a class, anywhere in your project, will be a Global variable e.g.

public static class MyGlobalVariables
{
    public static string MyGlobalString { get; set; }
}

But as @SLaks says, they can 'potentially' be bad practice and dangerous, if not handled correctly. For instance, in that above example, you would have multiple requests (threads) trying to access the same Property, which could be an issue if it was a complex type or a collection, you would have to implement some form of locking.

Sign up to request clarification or add additional context in comments.

4 Comments

My upvote. Actually, according to Microsoft, this is a preferred way - to use Global variables (static) because of performance. And Application object is used for compatibility with old ASP. Read more here: link. AFAIK both static and Application requires locks if think about thread safety and concurrency, because if Application is thread-safe, the data you are accessing may be not.
The static classes are not session safe, ie. in the same moment 2 simultaneous requests from 2 users will share the same variable, so this will mess up the data. To be user session safe I think must be something like abatishchev mentioned.
I agree with @Sunday and I think this one should mark as correct answer, however, the best way to do it is to implement a thread-safe singleton pattern, like: csharpindepth.com/Articles/General/Singleton.aspx
That is the best answer.
53
public static class GlobalVariables
{
    // readonly variable
    public static string Foo
    {
        get
        {
            return "foo";
        }
    }

    // read-write variable
    public static string Bar
    {
        get
        {
            return HttpContext.Current.Application["Bar"] as string;
        }
        set
        {
            HttpContext.Current.Application["Bar"] = value;
        }
    }
}

5 Comments

Why use Application class? Application object is used for compatibility with older ASP. Also, Microsoft says: "This increases performance because you can access a static variable faster than you can access an item in the Application dictionary". Source: link
@wishmesh: Agree. On other hand - will static variables be saved if database-based state machine is turned on?
You are correct. It seems that "static variable approach" may fail in web garden and other scenarios.
@abatishchev Why you not define your variable in Global.asax?, You are doing unusual typecasting on every request when you access the variable.
@Gupta: essentially both HttpContext and Global.asax are legacy approaches. Static variables is a better one, in general. But each has pros and cons, see the comment above. However ultimately you should have no shared variables, HTTP is stateless so should be your code.
24

You can put them in the Application:

Application["GlobalVar"] = 1234;

They are only global within the current IIS / Virtual applicition. This means, on a webfarm they are local to the server, and within the virtual directory that is the root of the application.

Comments

18

For non-static variables, I sorted it out via Application class dictionary as below:

At Global.asax.ac:

namespace MvcWebApplication 
{ 
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801 

    public class MvcApplication : System.Web.HttpApplication 
    { 
        private string _licensefile; // the global private variable

        internal string LicenseFile // the global controlled variable
        { 
            get 
            { 
                if (String.IsNullOrEmpty(_licensefile)) 
                { 
                    string tempMylFile = Path.Combine(Path.GetDirectoryName(Assembly.GetAssembly(typeof(LDLL.License)).Location), "License.l"); 
                    if (!File.Exists(tempMylFile)) 
                        File.Copy(Server.MapPath("~/Content/license/License.l"), 
                            tempMylFile, 
                            true); 
                    _licensefile = tempMylFile; 
                } 
                return _licensefile; 
            } 
        }
        protected void Application_Start()
        {
            Application["LicenseFile"] = LicenseFile;// the global variable's bed

            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
        }
    }
}

And in Controller:

namespace MvcWebApplication.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            return View(HttpContext.Application["LicenseFile"] as string);
        }

    }
}

In this way we can have global variables in ASP.NET MVC :)

NOTE: If your object is not string simply write:

return View(HttpContext.Application["X"] as yourType);

2 Comments

It should be noted that the essennce of your answer is "use the Application class dictionary.
@YasserZamani that's perfect. but how to modify the global variables in Controller? every time i changed the value, it lost in other requests.
8

You could also use a static class, such as a Config class or something along those lines...

public static class Config
{
    public static readonly string SomeValue = "blah";
}

Comments

0

The steel is far from hot, but I combined @abatishchev's solution with the answer from this post and got to this result. Hope it's useful:

public static class GlobalVars
{
    private const string GlobalKey = "AllMyVars";

    static GlobalVars()
    {
        Hashtable table = HttpContext.Current.Application[GlobalKey] as Hashtable;

        if (table == null)
        {
            table = new Hashtable();
            HttpContext.Current.Application[GlobalKey] = table;
        }
    }

    public static Hashtable Vars
    {
        get { return HttpContext.Current.Application[GlobalKey] as Hashtable; }
    }

    public static IEnumerable<SomeClass> SomeCollection
    {
        get { return GetVar("SomeCollection") as IEnumerable<SomeClass>; }
        set { WriteVar("SomeCollection", value); }
    }

    internal static DateTime SomeDate
    {
        get { return (DateTime)GetVar("SomeDate"); }
        set { WriteVar("SomeDate", value); }
    }

    private static object GetVar(string varName)
    {
        if (Vars.ContainsKey(varName))
        {
            return Vars[varName];
        }

        return null;
    }

    private static void WriteVar(string varName, object value)
    {
        if (value == null)
        {
            if (Vars.ContainsKey(varName))
            {
                Vars.Remove(varName);
            }
            return;
        }

        if (Vars[varName] == null)
        {
            Vars.Add(varName, value);
        }
        else
        {
            Vars[varName] = value;
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.