问题描述
我想复制到我的控制器中的一些代码中有这一行,但编译器抱怨
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 如果你想访问 web-servable 根路径(默认为 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 等价物是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!