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


    一、绝对路径

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

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

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

    var path =  Directory.GetCurrentDirectory()

    执行结果:

    E:project24-dingding-saasCodeDBen.Ding.SaaS.WebMobile

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

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

      2、或者通过其他方案。

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

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

    执行结果:

    E:project24-dingding-saasCodeDBen.Ding.SaaS.WebMobileinDebug
    etcoreapp2.0DBen.Ding.SaaS.WebMobile.dll

    二、相对路径

    从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;
                string contentRootPath = _hostingEnvironment.ContentRootPath;
    
                return Content(webRootPath + "
    " + contentRootPath);
            }
        }
    }
    复制代码

    执行结果:

    /Code/DBen.Ding.SaaS.WebMobile/wwwroot
    /Code/DBen.Ding.SaaS.WebMobile
  • 相关阅读:
    F# 语法概览
    Excel 帮助无法正常工作的解决方法
    autofac 组件的实例范围
    visual studio code 中隐藏从 ts 文件生成的 js 文件和 map 文件
    git vim 编辑器基本操作
    nhibernate 中 lazy="no-proxy" 时的问题
    什么是数据科学
    Elasticsearch 疑难解惑
    Hadoop MapReduce执行过程实例分析
    深入浅出JVM
  • 原文地址:https://www.cnblogs.com/ZaraNet/p/9949496.html
Copyright © 2020-2023  润新知