分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 软件开发

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

发布时间:2023-09-06 02:22责任编辑:傅花花关键词:暂无标签

一、绝对路径

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

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

执行结果:

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

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

原文地址:https://www.cnblogs.com/ZaraNet/p/9949496.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved