What is the equivalent of Server.MapPath in ASP.NET Core?

后端 未结 4 1161
清酒与你
清酒与你 2020-11-28 14:24

I have this line in some code I want to copy into my controller, but the compiler complains that

The name \'Server\' does not exist in the current con

4条回答
  •  情书的邮戳
    2020-11-28 14:53

    UPDATE: IHostingEnvironment is deprecated. See update below.

    In Asp.NET Core 2.2 and below, the hosting environment has been abstracted using the interface, IHostingEnvironment

    The ContentRootPath property will give you access to the absolute path to the application content files.

    You may also use the property, WebRootPath if you would like to access the web-servable root path (www folder by default)

    You may inject this dependency into your controller and access it as follows:

    public class HomeController : Controller
        {
            private readonly IHostingEnvironment _hostingEnvironment;
    
            public HomeController(IHostingEnvironment hostingEnvironment)
            {
                _hostingEnvironment = hostingEnvironment;
            }
    
            public ActionResult Index()
            {
                string webRootPath = _hostingEnvironment.WebRootPath;
                string contentRootPath = _hostingEnvironment.ContentRootPath;
    
                return Content(webRootPath + "\n" + contentRootPath);
            }
        }
    

    UPDATE

    IHostingEnvironment has been marked obsolete with .NET Core 3.0 as pointed out by @amir133. You should be using IWebHostEnvironment instead of IHostingEnvironment. Please refer to that answer below.

    Microsoft has neatly segregated the host environment properties among these interfaces. Please refer to the interface definition below:

    namespace Microsoft.Extensions.Hosting
    {
      public interface IHostEnvironment
      {
        string EnvironmentName { get; set; }
        string ApplicationName { get; set; }
        string ContentRootPath { get; set; }
        IFileProvider ContentRootFileProvider { get; set; }
      }
    }
    
    namespace Microsoft.AspNetCore.Hosting
    {
      public interface IWebHostEnvironment : IHostEnvironment
      {
        string WebRootPath { get; set; }
        IFileProvider WebRootFileProvider { get; set; }
      }
    }
    

提交回复
热议问题