ASP.NET MVC Global Variables

204,560

Solution 1

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

Solution 2

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.

Solution 3

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.

Solution 4

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

Solution 5

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";
}
Share:
204,560

Related videos on Youtube

Beginner
Author by

Beginner

I am a Beginner to everything

Updated on July 05, 2022

Comments

  • Beginner
    Beginner almost 2 years

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

    • Saurabh Gokhale
      Saurabh Gokhale about 13 years
      Your answer is - [MVC - How to declare global variables ](stackoverflow.com/questions/4171089/…) - Global variables in ASP.NET MVC
    • romanoza
      romanoza about 8 years
      @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.
  • Maris B.
    Maris B. about 12 years
    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.
  • Maris B.
    Maris B. about 12 years
    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
  • abatishchev
    abatishchev about 12 years
    @wishmesh: Agree. On other hand - will static variables be saved if database-based state machine is turned on?
  • Andrew Barber
    Andrew Barber almost 12 years
    It should be noted that the essennce of your answer is "use the Application class dictionary.
  • Maris B.
    Maris B. almost 12 years
    You are correct. It seems that "static variable approach" may fail in web garden and other scenarios.
  • Vasil Popov
    Vasil Popov over 11 years
    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.
  • Tohid
    Tohid over 11 years
    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
  • Sheldon Wei
    Sheldon Wei over 9 years
    @YasserZamani that's perfect. but how to modify the global variables in Controller? every time i changed the value, it lost in other requests.
  • Anirudha Gupta
    Anirudha Gupta about 8 years
    @abatishchev Why you not define your variable in Global.asax?, You are doing unusual typecasting on every request when you access the variable.
  • abatishchev
    abatishchev about 8 years
    @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.
  • Matheus Miranda
    Matheus Miranda almost 7 years
    That is the best answer.