小欢

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

电脑版发表于:2020/6/15 10:40

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

一、绝对路径

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

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

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

copy
var path =  Directory.GetCurrentDirectory()

执行结果:

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

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

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

  2、或者通过其他方案。

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

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

执行结果:

copy
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根目录和内容根目录的物理路径,如下所示:

copy
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);
        }
    }
}

执行结果:

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

转载地址:https://www.cnblogs.com/ZaraNet/p/9949496.html

关于TNBLOG
TNBLOG,技术分享。技术交流:群号677373950
ICP备案 :渝ICP备18016597号-1
App store Android
精彩评论
{{item.replyName}}
{{item.content}}
{{item.time}}
{{subpj.replyName}}
@{{subpj.beReplyName}}{{subpj.content}}
{{subpj.time}}
猜你喜欢