[英]HttpContext does not work in global.asax.cs
I have this code in the global.asax.cs 我在global.asax.cs中有此代码
protected void Application_Start(object sender, EventArgs e)
{
string logFile = HttpContext.Current.Request.PhysicalApplicationPath + "log4net.config";
}
It works fine in .NET 4.0, but throws the following exception when using in .NET 4.5. 它在.NET 4.0中工作正常,但在.NET 4.5中使用时引发以下异常。
Request is not available in this context
在这种情况下请求不可用
The answer is quite simple. 答案很简单。 First, this is not related to .NET version - rather, it is related to IIS version and ASP.NET mode.
首先,这与.NET版本无关-而是与IIS版本和ASP.NET模式有关。 The error message pretty much says it all - you can't use HttpContext in that location anymore (in fact, it doesn't exist yet).
错误消息几乎说明了一切-您不能再在该位置使用HttpContext(实际上,它尚不存在)。
That's related mainly to the changes that happened between Classical mode and Integrated mode (where ASP.NET is no longer an ISAPI dll, but rather integrated into IIS on a wholy different level). 这主要与经典模式和集成模式(ASP.NET不再是ISAPI dll,而是以完全不同的级别集成到IIS)之间发生的更改有关。 If I remember correctly, HttpContext now only exists for the duration of the request itself, starting with
BeginRequest
and ending with EndRequest
or somesuch. 如果我没记错的话,HttpContext现在仅在请求本身的持续时间内存在,以
BeginRequest
开始,以EndRequest
等结束。
If applicable, you could switch your application folder to a Classic Application pool in IIS, but I would advise against that, since Integrated mode is so much cooler. 如果适用,您可以将应用程序文件夹切换到IIS中的经典应用程序池,但是我建议不要这样做,因为集成模式要凉爽得多。 Only use Classic for legacy applications you can't upgrade.
仅将Classic用于无法升级的旧版应用程序。
Also, you shouldn't use PhysicalApplicationPath. 另外,您不应该使用PhysicalApplicationPath。 That's what
Server.MapPath
is for, or in the case of Application_start, HostingEnvironment.MapPath
. 这就是
Server.MapPath
的用途,对于Application_start而言, HostingEnvironment.MapPath
。
So you'd use 所以你会用
string logFile = HostingEnvironment.MapPath("~/log4net.config");
Error seems pretty clear - the Request
object is not available in that event. 错误似乎很明显-在该事件中
Request
对象不可用。
Try 尝试
HttpRuntime.AppDomainAppPath
or 要么
Server.MapPath(".")
instead. 代替。
For log4net, you could also use the regular method to set up your config location, such as: 对于log4net,您还可以使用常规方法来设置配置位置,例如:
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "MyStandardLog4Net.config", Watch = true)] [程序集:log4net.Config.XmlConfigurator(ConfigFile =“ MyStandardLog4Net.config”,Watch = true)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.