Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpApplicationState not available in an MVC controller

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

like image 661
Mehrdad Avatar asked Jul 09 '10 14:07

Mehrdad


People also ask

What does controller contain in MVC?

A controller is responsible for controlling the way that a user interacts with an MVC application. A controller contains the flow control logic for an ASP.NET MVC application. A controller determines what response to send back to a user when a user makes a browser request.

How does MVC know which controller to use?

This is because of conventions. The default convention is /{controller}/{action} , where the action is optional and defaults to Index . So when you request /Scott , MVC's routing will go and look for a controller named ScottController , all because of conventions.

How can I get controller in MVC?

In Solution Explorer, right-click the Controllers folder and then click Add, then Controller. In the Add Scaffold dialog box, click MVC 5 Controller with views, using Entity Framework, and then click Add.


2 Answers

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 
like image 82
utunga Avatar answered Oct 08 '22 19:10

utunga


In ASP.NET MVC2, i use

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

and to get

HttpContext.Application["foo"]
like image 21
eka808 Avatar answered Oct 08 '22 18:10

eka808