Here Santosh Kumar Singh has explained why Server.MapPath not working in ASP.Net Core and what is the alternative solution for using the functionality in ASP.Net Core.
Microsoft has permanently removed Server.MapPath function from .Net Core and introduced a new interfaces IHostingEnvironment for .Net Core 2.0 and IWebHostEnvironment for .Net Core 3.0.
In this article I will explain why Server.MapPath not working in ASP.Net Core and what is the alternative solution for using the functionality in ASP.Net Core.
Microsoft has permanently removed Server.MapPath function from .Net Core and introduced a new interfaces IHostingEnvironment for .Net Core 2.0 and IWebHostEnvironment for .Net Core 3.0.
What are IHostingEnvironment and IWebHostEnvironment
The IHostingEnvironment is an interface for .Net Core 2.0 and IWebHostEnvironment has replaced IHostingEnvironment in .Net Core 3.0.
Both these interfaces need to be injected as dependency in the Controller and then later used throughout the Controller.
Both these interfaces have two properties.
1. WebRootPath – Path of the www folder.
2. ContentRootPath – Path of the root folder which contains all the Application files.
Namespaces
You will need to import the following namespace.
using Microsoft.AspNetCore.Hosting;
Using IHostingEnvironment
In the below example, the IHostingEnvironment is injected in the Controller and assigned to the private property Environment and later used to get the WebRootPath and ContentRootPath.
public class HomeController : Controller
{
private IHostingEnvironment Environment;
public HomeController(IHostingEnvironment _environment)
{
Environment = _environment;
}
public IActionResult Index()
{
string wwwPath = this.Environment.WebRootPath;
string contentPath = this.Environment.ContentRootPath;
return View();
}
}
Using IWebHostEnvironment
In the below example, the IWebHostEnvironment is injected in the Controller and assigned to the private property Environment and later used to get the WebRootPath and ContentRootPath.
public class HomeController : Controller
{
private IWebHostEnvironment Environment;
public HomeController(IWebHostEnvironment _environment)
{
Environment = _environment;
}
public IActionResult Index()
{
string wwwPath = this.Environment.WebRootPath;
string contentPath = this.Environment.ContentRootPath;
return View();
}
}
Output:
wwwPath ="ApplicationName\\wwwroot";
contentPath ="ApplicationName";
No comments:
Post a Comment