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
Error seems pretty clear - the Request
object is not available in that event.
Try
HttpRuntime.AppDomainAppPath
or
Server.MapPath(".")
instead.
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");
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)]