gpt4 book ai didi

c# - 访问 ApplicationState 变量

转载 作者:太空宇宙 更新时间:2023-11-03 10:36:26 27 4
gpt4 key购买 nike

我正在浏览这里的文档:http://msdn.microsoft.com/en-us/library/ms178594%28v=vs.140%29.aspx为了创建一个变量来告诉程序它是否在本地环境中。

这就是我在 Global.asax.cs 中的内容:

namespace website
{
public class MvcApplication : System.Web.HttpApplication
{
...
Application["loc"] = false;
if (Request.Headers["host"].Contains("localhost"))
{
Application["loc"] = true;
}
}
}

当我尝试像这样访问模型文件中的 ApplicationState 变量时:

if (Application["loc"] != null)
{
bool loc = (bool)Application["loc"];
}

这正是它在文档中指定的方式,我得到一个错误:

The Name Application does not exist in the current context.

我做错了什么?

最佳答案

Application是在 HttpApplication 上定义的实例级属性。如果没有 HttpApplication 的实例,您将无法尝试访问它。

可以通过静态属性获取对当前 HttpApplication 的引用 HttpContext.Current这将返回一个 HttpContext 对象;这个可以be further queried获取实际的 HttpApplication,

例如

var myHttpApp = HttpContext.Current.ApplicationInstance;
var appState = myHttpApp.Application;

你也可以直接使用HttpContext.Current.Application获取对当前 HttpApplicationState 对象的引用。

要修复您的代码,您可以这样做:

if (HttpContext.Current.Application["loc"] != null)
{
bool loc = (bool)(HttpContext.Current.Application["loc"]);
}

关于c# - 访问 ApplicationState 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27571602/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com