7

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

Omu
  • 69,856
  • 92
  • 277
  • 407
  • Although late, see my answer to a similar question: https://stackoverflow.com/questions/30656089/reading-a-file-in-mvc-6/35459834#35459834. – Alexander Christov Sep 28 '17 at 07:00

2 Answers2

13

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;
Omu
  • 69,856
  • 92
  • 277
  • 407
regnauld
  • 4,046
  • 3
  • 23
  • 22
3

recommended Solution

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.


Another Solution

(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.

Amir133
  • 2,372
  • 2
  • 18
  • 34