我在一些要复制到 Controller 中的代码中有这一行,但编译器提示说
The name 'Server' does not exist in the current context
var UploadPath = Server.MapPath("~/App_Data/uploads")
如何在 ASP.NET Core 中实现等价物?
请您参考如下方法:
.Net 6(.NetCore 3 及以上)
例如我想定位 ~/wwwroot/CSS
public class YourController : Controller
{
private readonly IWebHostEnvironment _webHostEnvironment;
public YourController (IWebHostEnvironment webHostEnvironment)
{
_webHostEnvironment= webHostEnvironment;
}
public IActionResult Index()
{
string webRootPath = _webHostEnvironment.WebRootPath;
string contentRootPath = _webHostEnvironment.ContentRootPath;
string path ="";
path = Path.Combine(webRootPath , "CSS");
//or path = Path.Combine(contentRootPath , "wwwroot" ,"CSS" );
return View();
}
}
一些技巧
此外,如果您没有 Controller 或服务,请按照最后一部分并将其类注册为单例。
然后,在 Startup.ConfigureServices 中:
services.AddSingleton<your_class_Name>();
最后注入(inject)
your_class_Name
你需要它的地方。
.Net 核心 2
例如我想定位
~/wwwroot/CSS
public class YourController : Controller
{
private readonly IHostingEnvironment _HostEnvironment; //diference is here : IHostingEnvironment vs I*Web*HostEnvironment
public YourController (IHostingEnvironment HostEnvironment)
{
_HostEnvironment= HostEnvironment;
}
public ActionResult Index()
{
string webRootPath = _HostEnvironment.WebRootPath;
string contentRootPath = _HostEnvironment.ContentRootPath;
string path ="";
path = Path.Combine(webRootPath , "CSS");
//or path = Path.Combine(contentRootPath , "wwwroot" ,"CSS" );
return View();
}
}
更多细节
感谢@Ashin 但
IHostingEnvironment
在 MVC 核心 3 中已过时!!
根据 this :
过时的类型(警告):
Microsoft.Extensions.Hosting.IHostingEnvironment
Microsoft.AspNetCore.Hosting.IHostingEnvironment
Microsoft.Extensions.Hosting.IApplicationLifetime
Microsoft.AspNetCore.Hosting.IApplicationLifetime
Microsoft.Extensions.Hosting.EnvironmentName
Microsoft.AspNetCore.Hosting.EnvironmentName
新类型:
Microsoft.Extensions.Hosting.IHostEnvironment
Microsoft.AspNetCore.Hosting.IWebHostEnvironment : IHostEnvironment
Microsoft.Extensions.Hosting.IHostApplicationLifetime
Microsoft.Extensions.Hosting.Environments
所以你必须使用
IWebHostEnvironment
而不是
IHostingEnvironment
.