1. 程式人生 > >.Net Core api 中獲取應用程式物理路徑wwwroot

.Net Core api 中獲取應用程式物理路徑wwwroot

如果要得到傳統的ASP.Net應用程式中的相對路徑或虛擬路徑對應的伺服器物理路徑,只需要使用使用Server.MapPath()方法來取得Asp.Net根目錄的物理路徑,如下所示:

// Classic ASP.NET
public class HomeController : Controller
{
    public ActionResult Index()
    {
        string physicalWebRootPath = Server.MapPath("~/");
        
        return Content(physicalWebRootPath);
    }
}

但是在ASPNET Core中不存在Server.MapPath()方法,Controller基類也沒有Server屬性。

 

在Asp.Net Core中取得物理路徑:

從ASP.NET Core RC2開始,可以通過注入 IHostingEnvironment 服務物件來取得Web根目錄和內容根目錄的物理路徑,如下所示:

using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;

namespace AspNetCorePathMapping
{
    public
class HomeController : Controller { private readonly IHostingEnvironment _hostingEnvironment; public HomeController(IHostingEnvironment hostingEnvironment) { _hostingEnvironment = hostingEnvironment; } public ActionResult Index() {
string webRootPath = _hostingEnvironment.WebRootPath; //F:\資料字典\Centa.Data.Dictionary\Centa.Data.Web\wwwroot string contentRootPath = _hostingEnvironment.ContentRootPath; //F:\資料字典\Centa.Data.Dictionary\Centa.Data.Web return Content(webRootPath + "\n" + contentRootPath); } } }

ASP.NET Core RC1

在ASP.NET Core RC2之前 (就是ASP.NET Core RC1或更低版本),通過 IApplicationEnvironment.ApplicationBasePath 來獲取 Asp.Net Core應用程式的根目錄(物理路徑) :

using Microsoft.AspNet.Mvc;
using Microsoft.Extensions.PlatformAbstractions;

namespace AspNetCorePathMapping
{
    public class HomeController : Controller
    {
        private readonly IApplicationEnvironment _appEnvironment;

        public HomeController(IApplicationEnvironment appEnvironment)
        {
            _appEnvironment = appEnvironment;
        }

        public ActionResult Index()
        {
            return Content(_appEnvironment.ApplicationBasePath);
        }
    }
}