having a helper method like this:
public static IHtmlContent Source(this IHtmlHelper html, string s)
{
var path = ServerMapPath() + "Views\\" + s;
I need to get the equivalent of Server.MapPath in asp.net core
having a helper method like this:
public static IHtmlContent Source(this IHtmlHelper html, string s)
{
var path = ServerMapPath() + "Views\\" + s;
I need to get the equivalent of Server.MapPath in asp.net core
You need to inject IHostingEnvironment
. Then:
var path = env.ContentRootPath + "Views\\" + s;
in an html helper you can do this:
((IHostingEnvironment)html.ViewContext.HttpContext.RequestServices.GetService(typeof(IHostingEnvironment))).ContentRootPath;
I recommend Don't use a static class. You can keep something similar to your class, and register it as a singleton.
public class SourceClass
{
private readonly IWebHostEnvironment _webHostEnvironment;
public SourceClass (IWebHostEnvironment webHostEnvironment)
{
_webHostEnvironment= webHostEnvironment;
}
private IHtmlContent Source(this IHtmlHelper html, string s)
{
string contentRootPath = _webHostEnvironment.ContentRootPath;
Path.Combine(contentRootPath,"Views",s)
}
}
Then, in Startup.ConfigureServices:
services.AddSingleton<SourceClass>();
Finally, inject SourceClass
where you need it, instead of just statically referencing the class.
(Note :@regnauld provided this solution, but it had some drawbacks, which I thought would be fully answered)
But if you want to use a static method you can do(Note: In .Net Core 3 IHostingEnvironment
is absolute and IWebHostEnvironment
must be used instead ):
for ServerPath ,use
((IWebHostEnvironment)html.ViewContext.HttpContext.RequestServices.GetService(typeof(IWebHostEnvironment))).ContentRootPath
OR
for WebRootPath (wwwroot) ,use
((IWebHostEnvironment)html.ViewContext.HttpContext.RequestServices.GetService(typeof(IWebHostEnvironment))).WebRootPath
in this answer you can find more details.
I also recommend that you use this code:
var path = Path.Combine(WebRootPath,"Views",s)
instead of
var path = WebRootPath + "Views\\" + s
to run the code on all operating systems.