Server.MapPath Equivalent in ASP.NET Core 2

Raymond Raymond visibility 20,967 event 2017-10-08 access_time 4 years ago language English

Background

In traditional asp.net applications, Server.MapPath is commonly used to generate absolute path in the web server. However, this has been removed from ASP.NET Core. So what is the equivalent way of doing it?

IHostingEnvironment

In ASP.NET Core, all the severable resources are located in wwwroot folder and the whole site is actually an ‘Console’ application.  To access that folder, we can use IHostingEnvironment.WebRootPath property.

Sample Code

IHostingEnvironment is injected and can be consumed in any controller or services.

private readonly IHostingEnvironment environment;
        public MetaWeblogXmlRpcService(
             IHostingEnvironment environment)
         {
             this.environment = environment;
         }

And then in your code, you can reference

var blogImageFolder = Path.Combine(environment.WebRootPath, imageFolder, blog.UniqueName);

The path information can then be used to manipulate I/O operations and etc..

How to Generate Absolute Url in non-MVC context

In your middleware or other scenarios, you may not have access to UrlHelper as you can do in MVC controller or views. Under this situation, you can still build absolute URL with HttpContext.

* In Middleware, you can inject HttpContext instance.

                 var imageVirtualPath = Path.Combine(imageFolder, blog.UniqueName, fileName);
                 var request = HttpContext.Request;
                 var uriBuilder = new UriBuilder
                 {
                     Host = request.Host.Host,
                     Scheme = request.Scheme,
                     Path = imageVirtualPath
                 };
                if (request.Host.Port.HasValue)
                     uriBuilder.Port = request.Host.Port.Value;
                var url = uriBuilder.ToString();
More from Kontext
info Last modified by Raymond 4 years ago copyright This page is subject to Site terms.
comment Comments
Raymond Raymond access_time 5 years ago more_vert
#180 Re: Server.MapPath Equivalent in ASP.NET Core 2

I'm glad it helped. :) It took me a while when I migrated my website to .NET Core a few years ago.

format_quote

person TaterHead access_time 5 years ago
Re: Server.MapPath Equivalent in ASP.NET Core 2

Thanks... perfect!  New to Core (2.2) ... I was wondering where Server.MapPath() went!

T TaterHead access_time 5 years ago more_vert
#99 Re: Server.MapPath Equivalent in ASP.NET Core 2

Thanks... perfect!  New to Core (2.2) ... I was wondering where Server.MapPath() went!

Please log in or register to comment.

account_circle Log in person_add Register

Log in with external accounts