10

I'm using MVC2 and VS2010 developing a website and need to use Application State global values. I can set a value like 'Application["hits"]=0;' in Global.asax but when trying to use the same in an MVC controller always get the following error:

The name 'Application' does not exist in the current context

I have also tried using in the Global.asax in order to define a global variable but it triggers the following error:

A namespace cannot directly contain members such as fields or methods

I'm looking for a way to define global Application State values that are available within all controllers of my MVC2 web application. Am I omitting something? My controller looks like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MVCApplication.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            Application["hits"] += 1;

            ViewData["Message"] = "Welcome to ASP.NET MVC!";
            return View();
        }

    }
}

I appreciate any solutions and/or suggestions.

Thanks Mehrdad

Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
Mehrdad
  • 149
  • 3
  • 11

3 Answers3

11

I think that in MVC3 you can get access to an actual HttpApplicationState object via the

HttpContext.ApplicationInstance

property. That is:

HttpApplicationState application = HttpContext.ApplicationInstance.Application 
utunga
  • 468
  • 5
  • 15
2

In ASP.NET MVC2, i use

HttpContext.Application["foo"] = "bar";

and to get

HttpContext.Application["foo"]
eka808
  • 2,257
  • 3
  • 29
  • 41
0

You could use a static class with an internal dictionary and an indexer.

Also, have you tried HttpContext.Current.Application?

Jaroslav Jandek
  • 9,463
  • 1
  • 28
  • 30
  • Thanks Jaroslav, the problem is now solved using the following in the controllers: HttpContext.Application["hits"] – Mehrdad Jul 09 '10 at 15:02