HttpContext does not work in global.asax.cs

試著忘記壹切 提交于 2019-12-21 23:06:38

问题


I have this code in the 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.

Request is not available in this context


回答1:


Error seems pretty clear - the Request object is not available in that event.

Try

HttpRuntime.AppDomainAppPath 

or

Server.MapPath(".")

instead.




回答2:


The answer is quite simple. First, this is not related to .NET version - rather, it is related to IIS version and ASP.NET mode. The error message pretty much says it all - you can't use HttpContext in that location anymore (in fact, it doesn't exist yet).

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). If I remember correctly, HttpContext now only exists for the duration of the request itself, starting with BeginRequest and ending with EndRequest or somesuch.

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. Only use Classic for legacy applications you can't upgrade.

Also, you shouldn't use PhysicalApplicationPath. That's what Server.MapPath is for, or in the case of Application_start, HostingEnvironment.MapPath.

So you'd use

string logFile = HostingEnvironment.MapPath("~/log4net.config");



回答3:


For log4net, you could also use the regular method to set up your config location, such as:

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "MyStandardLog4Net.config", Watch = true)]



来源:https://stackoverflow.com/questions/20686131/httpcontext-does-not-work-in-global-asax-cs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!