[c#] ASP.NET MVC Global Variables

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

This question is related to c# .net asp.net asp.net-mvc global-variables

The answer is


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.


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.


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";
}

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);

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;
        }
    }
}

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to asp.net-mvc

Using Lato fonts in my css (@font-face) Better solution without exluding fields from Binding Vue.js get selected option on @change You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to send json data in POST request using C# VS 2017 Metadata file '.dll could not be found The default XML namespace of the project must be the MSBuild XML namespace How to create roles in ASP.NET Core and assign them to users? The model item passed into the dictionary is of type .. but this dictionary requires a model item of type How to use npm with ASP.NET Core

Examples related to global-variables

What is the best way to declare global variable in Vue.js? How do I turn off the mysql password validation? How to declare Global Variables in Excel VBA to be visible across the Workbook How to create a global variable? global variable for all controller and views How to define global variable in Google Apps Script How to modify a global variable within a function in bash? Using a global variable with a thread Is it possible to use global variables in Rust? How to access global js variable in AngularJS directive