ASP.NET Core 中 Server.MapPath 的等价物是什么? [英] What is the equivalent of Server.MapPath in ASP.NET Core?

查看:29
本文介绍了ASP.NET Core 中 Server.MapPath 的等价物是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想复制到我的控制器中的一些代码中有这一行,但编译器抱怨

I have this line in some code I want to copy into my controller, but the compiler complains that

名称服务器"在当前上下文中不存在

The name 'Server' does not exist in the current context

var UploadPath = Server.MapPath("~/App_Data/uploads")

我怎样才能在 ASP.NET Core 中实现等价的?

How can I achieve the equivalent in ASP.NET Core?

推荐答案

更新:不推荐使用 IHostingEnvironment.请参阅下面的更新.

在 Asp.NET Core 2.2 及以下版本中,托管环境已使用接口抽象化,IHostingEnvironment

In Asp.NET Core 2.2 and below, the hosting environment has been abstracted using the interface, IHostingEnvironment

ContentRootPath 属性将使您能够访问应用程序内容文件的绝对路径.

The ContentRootPath property will give you access to the absolute path to the application content files.

您也可以使用该属性,WebRootPath 如果您想访问网络服务的根路径(默认为 www 文件夹)

You may also use the property, WebRootPath if you would like to access the web-servable root path (www folder by default)

您可以将此依赖项注入您的控制器并按如下方式访问它:

You may inject this dependency into your controller and access it as follows:

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

更新 - .NET CORE 3.0 及更高版本

正如@amir133 所指出的那样,IHostingEnvironment 已被 .NET Core 3.0 标记为过时.您应该使用 IWebHostEnvironment 而不是 IHostingEnvironment.请参考下面的答案.

IHostingEnvironment has been marked obsolete with .NET Core 3.0 as pointed out by @amir133. You should be using IWebHostEnvironment instead of IHostingEnvironment. Please refer to that answer below.

Microsoft 在这些接口之间巧妙地隔离了主机环境属性.请参考下面的接口定义:

Microsoft has neatly segregated the host environment properties among these interfaces. Please refer to the interface definition below:

namespace Microsoft.Extensions.Hosting
{
  public interface IHostEnvironment
  {
    string EnvironmentName { get; set; }
    string ApplicationName { get; set; }
    string ContentRootPath { get; set; }
    IFileProvider ContentRootFileProvider { get; set; }
  }
}

namespace Microsoft.AspNetCore.Hosting
{
  public interface IWebHostEnvironment : IHostEnvironment
  {
    string WebRootPath { get; set; }
    IFileProvider WebRootFileProvider { get; set; }
  }
}

这篇关于ASP.NET Core 中 Server.MapPath 的等价物是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆