问题描述
我正在使用MVC2和VS2010开发一个网站,并且需要使用Application State全局值。我可以在Global.asax中设置一个类似'Application [hits] = 0;'的值,但是当试图在MVC控制器中使用相同的值时总会出现以下错误:
名称'Application'在当前上下文中不存在
我也尝试在Global.asax中使用以定义全局变量,但它触发以下错误:
命名空间不能直接包含字段或方法等成员。
我在寻找一种定义全局应用程序状态值的方法,这些值可在我的MVC2 Web应用程序的所有控制器中使用。我省略了什么吗?我的控制器看起来像这样:
using System;
使用System.Collections.Generic;
使用System.Linq;
使用System.Web;
使用System.Web.Mvc;
namespace MVCApplication.Controllers
{
[HandleError]
public class HomeController:Controller
{
public ActionResult Index()
{
Application [hits] + = 1;
ViewData [Message] =欢迎使用ASP.NET MVC!;
return View();
}
}
}
我欣赏任何解决方案和/或建议。
感谢
Mehrdad
在MVC3中,你可以通过
来访问实际的HttpApplicationState对象。
属性。即:
pre $ HttpApplicationState application = HttpContext.ApplicationInstance.Application
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.
ThanksMehrdad
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
这篇关于HttpApplicationState在MVC控制器中不可用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!