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

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

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

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

 

在Asp.Net Core中取得物理路径:

从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;           //F:\数据字典\Centa.Data.Dictionary\Centa.Data.Web\wwwroot
            string contentRootPath = _hostingEnvironment.ContentRootPath;   //F:\数据字典\Centa.Data.Dictionary\Centa.Data.Web

            return Content(webRootPath + "\n" + contentRootPath);
        }
    }
}

ASP.NET Core RC1

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

 

转载于:https://www.cnblogs.com/gygtech/p/9909222.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值