Skip to main content
 首页 » 编程设计

asp.net之ASP.NET Core 中的 Server.MapPath 等价物是什么

2024年11月24日10傻小

我在一些要复制到 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 .