再见了Server对象,拥抱IHostingEnvironment服务对象(.net core)

时间:2023-03-09 00:42:12
再见了Server对象,拥抱IHostingEnvironment服务对象(.net core)

一、绝对路径

1、获取应用程序运行当前目录Directory.GetCurrentDirectory()。

System.IO命名空间中存在Directory类,提供了获取应用程序运行当前目录的静态方法GetCurrentDirectory,

但根据.net core的设计,此方法不是真正的获取应用程序的当前方法,而是执行dotnet命令所在目录,

var path =  Directory.GetCurrentDirectory()

执行结果:

E:\project\24-dingding-saas\Code\DBen.Ding.SaaS.WebMobile

要获取应用程序运行当前目录,只能通过变通的方案解决。

如:1、在应用程序的目录执行dotnet命令,

  2、或者通过其他方案。

如下代码是一种可以获取应用程序的当前目录:

 dynamic type = (new Program()).GetType();
string currentDirectory = Path.GetDirectoryName(type.Assembly.Location);
Console.WriteLine(currentDirectory);

执行结果:

E:\project\24-dingding-saas\Code\DBen.Ding.SaaS.WebMobile\bin\Debug\netcoreapp2.0\DBen.Ding.SaaS.WebMobile.dll

二、相对路径

从ASP.NET Core RC2开始,可以通过注入 IHostingEnvironment 服务对象来取得Web根目录和内容根目录的物理路径,如下所示:

再见了Server对象,拥抱IHostingEnvironment服务对象(.net core)
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;
string contentRootPath = _hostingEnvironment.ContentRootPath; return Content(webRootPath + "\n" + contentRootPath);
}
}
}
再见了Server对象,拥抱IHostingEnvironment服务对象(.net core)

执行结果:

/Code/DBen.Ding.SaaS.WebMobile/wwwroot
/Code/DBen.Ding.SaaS.WebMobile