Alternative for Server.MapPath()

What to do when HttpContext.Server is null and you can not access anything inside it? In addition to this problem, the MapPath function throws an error: System.Web.HttpException (0x80004005): Request is not available in this context.

Your problematic code might looks like this:

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

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

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

            // ... code
        }

It seems you are trying to access a property that only receives a reference when we have an actuall HTTP call. The most common place is when you try to call this method from inside your Global.asax.

Note: The Application_Start function is triggered just once, and it happens when the web application starts via IIS start/restart or recycling your app pool or modifying your Web.Config file.

Use: HostingEnvironment.MapPath(string)

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

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

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

            // ... code
        }

The funny thing is that Server.MapPath() will call the HostingEnvironment.MapPath(), and the only thing you have to worry about is to avoid null strings on HostingEnvironment.MapPath parameter, it will raise an exception.

There is no difference with the responding string, so you can jump straight to HostingEnvironment.MapPath().

Hope it helps! Happy coding.

This entry was posted in Programming and tagged , . Bookmark the permalink.

Leave a Reply

Please note that all fields are required. In order to keep the site clean and free of any subscription to comment, please do not post ads, no spam, no link dropping, no domain names. Your e-mail will not be published. All comments are moderated (they will appear shortly). rel="nofollow" in use: no page rank will be considered for links here. All fields are required. Thank you to share your thoughts :-)

*