ASP.NET Core: Replacement for Server.MapPath
his blog post shows how application and public web files are organized in ASP.NET Core and how to access them from web applications.
Join the DZone community and get the full member experience.
Join For FreeASP.NET Core offers two different locations for files:
- Content root - this is where application binaries and other private files are held.
- Web root - this is where public files are held (wwwroot folder in web project).
By default, web root is located under content root. But there are also deployments where web root is located somewhere else. I have previously seen such deployments on Azure Web Apps. It's possible that some ISPs also use different directories in trees for application files and web root.
Getting Content and Web Root in Code
Paths to content root and web root are available through IHostingEnvironment in code, as shown here.
Notice how content root and wwwroot are located in totally different places in the machine.
Setting Web Root's Location
To set a location for web root we need the hosting.json file in the application root folder. Also, we need some code to include in the file — at least for Kestrel. My hosting.json is shown here.
{
"webRoot": "c:\\temp\\wwwroot\\"
}
It is loaded when the program starts (Program.cs file). I made this file optional so my application doesn't crash when the hosting file is missing.
public class Program
{
public static void Main(string[] args)
{
var config = new ConfigurationBuilder()
.AddJsonFile("hosting.json", optional: true)
.Build();
CreateWebHostBuilder(args).UseConfiguration(config)
.UseKestrel()
.Build()
.Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
If there is no hosting file, then the default configuration is used and ASP.NET Core expects that web root is located under the application's content root.
Wrapping Up
Although we don't have a Server.MapPath()
call anymore in ASP.NET, we have IHostingEnvironment which provides us with paths to the application content root and web root. These are full paths to the mentioned locations and not URLs. We can use these paths to read files from both of locations if needed.
Published at DZone with permission of Gunnar Peipman, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments