How to get absolute path in ASP.Net Core alternative way for Server.MapPath

前端 未结 5 1583
野的像风
野的像风 2020-12-02 18:39

How to get absolute path in ASP net core alternative way for Server.MapPath

I have tried to use IHostingEnvironment

5条回答
  •  生来不讨喜
    2020-12-02 18:48

    .Net Core 3

    For example I want to locate ~/wwwroot/CSS

    public class YourController : Controller 
    {
        private readonly IWebHostEnvironment _webHostEnvironment;
    
        public YourController (IWebHostEnvironment webHostEnvironment)
        {
            _webHostEnvironment= webHostEnvironment;
        }
    
        public IActionResult Index()
        {
            string webRootPath = _webHostEnvironment.WebRootPath;
            string contentRootPath = _webHostEnvironment.ContentRootPath;
    
            string path ="";
            path = Path.Combine(webRootPath , "CSS");
            //or path = Path.Combine(contentRootPath , "wwwroot" ,"CSS" );
            return View();
        }
    }
    

    Some Tricks

    Also if you don't have a controller or service,follow last Part and register it's class as a singleton. Then, in Startup.ConfigureServices:

    services.AddSingleton();
    

    Finally, inject your_class_Name where you need it.


    .Net Core 2

    For example I want to locate ~/wwwroot/CSS

    public class YourController : Controller
    {
        private readonly IHostingEnvironment _HostEnvironment;
    
        public YourController (IHostingEnvironment HostEnvironment)
        {
            _HostEnvironment= HostEnvironment;
        }
    
        public ActionResult Index()
        {
            string webRootPath = _HostEnvironment.WebRootPath;
            string contentRootPath = _HostEnvironment.ContentRootPath;
    
            string path ="";
            path = Path.Combine(webRootPath , "CSS");
            //or path = Path.Combine(contentRootPath , "wwwroot" ,"CSS" );
            return View();
        }
    }
    

    MoreDetails

    Thanks to @NKosi but IHostingEnvironment is obsoleted in MVC core 3!!

    according to this :

    Obsolete types (warning):

    Microsoft.Extensions.Hosting.IHostingEnvironment
    Microsoft.AspNetCore.Hosting.IHostingEnvironment
    Microsoft.Extensions.Hosting.IApplicationLifetime
    Microsoft.AspNetCore.Hosting.IApplicationLifetime
    Microsoft.Extensions.Hosting.EnvironmentName
    Microsoft.AspNetCore.Hosting.EnvironmentName
    

    New types:

    Microsoft.Extensions.Hosting.IHostEnvironment
    Microsoft.AspNetCore.Hosting.IWebHostEnvironment : IHostEnvironment
    Microsoft.Extensions.Hosting.IHostApplicationLifetime
    Microsoft.Extensions.Hosting.Environments 
    

    So you must use IWebHostEnvironment instead of IHostingEnvironment.

提交回复
热议问题