Server.MapPath fails within Global.asax

8

In the code below, when I try to call the MapPath function inside Global.asax, a run-time error occurs with the following error message:

  System.Web.HttpException (0 × 80004005): Request is not available in   this context.

The faulty code is:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);

    string path = HttpContext.Server.MapPath("~/assets/all.js")

    // ... code
}

How to use a MapPath function in Global.asax?

    
asked by anonymous 12.12.2013 / 17:25

3 answers

6

The problem is actually in HttpContext.Server.MapPath . The problem occurs because when called in Application_Start , there is an Http context. This context only exists when there is an HTTP call.

Application_Start occurs only when your web application is started via Start / Restart in IIS, recycling App Pool, and so on. Because there is no HTTP context, you should use the context of the environment.

Change the HttpContext to HostingEnvironment.MapPath :

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);

    string path = HostingEnvironment.MapPath("~/assets/all.js")

    // ... code
}

The Server.MapPath () itself calls the HostingEnvironment.MapPath (). The only difference that matters in the context of this question is that you need to make sure that the string passed in the parameter is never null, otherwise an Exception will be fired.

    
12.12.2013 / 17:25
1

HttpContext is only available when someone makes an HTTP call (such as going to the site through a browser).

In this sense, it is not possible to use the function as described, in the place where it is in Application_Start . However, even though the question is about Global.ascx , the line

string path = HttpContext.Server.MapPath("~/assets/all.js")

This is a completely valid code if it is used inside a Controller or View (using MVC ) or Code Behind (using ASP.NET webforms).

    
31.01.2014 / 21:40
-1

Try:

System.Web.Hosting.HostingEnvironment.MapPath();
    
16.10.2015 / 20:09