Server.Mappath fails within Global.asax

Asked

Viewed 424 times

8

In the code below, when I try to call the Mappath function inside Global.asax, an error occurs at runtime with the following error message:

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

The defective 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?

3 answers

6

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

The Application_start occurs only when your web application is started via Start/Restart on IIS, recycling the App Pool, among other ways. Since there is no HTTP context, you should use the environment context.

Switch Httpcontext to HostingEnvironment.MapPath:

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

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

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

    // ... code
}

Server.Mappath() itself calls 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 triggered.

  • 1

    Note: The one previously used HttpContext.Current is no longer available on Application_Start in IIS version 7. If the application is hosted in a previous version or mode classic the context will be available. But of course, I do not recommend this dependency :)

1

The HttpContext is only available when someone makes an HTTP call (like 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 the Application_Start. However, even though you know the question is about Global.ascx, the line

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

is fully valid code if used within a Controller or View (using MVC) or the Code Behind (using webforms from ASP.NET).

-1

Try:

System.Web.Hosting.HostingEnvironment.MapPath();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.