900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > ASPNET Core api 中获取应用程序物理路径wwwroot

ASPNET Core api 中获取应用程序物理路径wwwroot

时间:2021-08-25 18:55:32

相关推荐

ASPNET Core api 中获取应用程序物理路径wwwroot

如果要得到传统的应用程序中的相对路径或虚拟路径对应的服务器物理路径,只需要使用使用Server.MapPath()方法来取得根目录的物理路径,如下所示:

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

但是在ASPNET Core中不存在Server.MapPath()方法,Controller基类也没有Server属性。

在 Core中取得物理路径:

从 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/AspNetCorePathMapping目录下创建了一个示例 Core 应用程序,当我运行时,控制器将返回以下两个路径:

这里要注意区分Web根目录 和 内容根目录的区别:

Web根目录是指提供静态内容的根目录,即 core应用程序根目录下的wwwroot目录

内容根目录是指应用程序的根目录,即 core应用的应用程序根目录

Core RC1

在 Core RC2之前 (就是 Core RC1或更低版本),通过IApplicationEnvironment.ApplicationBasePath来获取 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);}}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。