有一个这样的辅助方法:
public static IHtmlContent Source(this IHtmlHelper html, string s)
{
var path = ServerMapPath() + "Views\\" + s;
我需要在 asp.net 核心中获得等效的 Server.MapPath
最佳答案
推荐解决方案
我 推荐不要使用静态类。您可以保留与您的类(class)类似的内容,并将其注册为单例。
public class SourceClass
{
private readonly IWebHostEnvironment _webHostEnvironment;
public SourceClass (IWebHostEnvironment webHostEnvironment)
{
_webHostEnvironment= webHostEnvironment;
}
private IHtmlContent Source(this IHtmlHelper html, string s)
{
string contentRootPath = _webHostEnvironment.ContentRootPath;
Path.Combine(contentRootPath,"Views",s)
}
}
然后,在 Startup.ConfigureServices 中:
services.AddSingleton<SourceClass>();
最后注入(inject)
SourceClass
在你需要的地方,而不是仅仅静态引用类。另一种解决方案
(注意:@regnauld 提供了这个解决方案,但它有一些缺点,我认为会得到充分的回答)
但是如果你想使用静态方法,你可以这样做(注意:在 .Net Core 3
IHostingEnvironment
是绝对的,必须使用 IWebHostEnvironment
代替):((IWebHostEnvironment)html.ViewContext.HttpContext.RequestServices.GetService(typeof(IWebHostEnvironment))).ContentRootPath
或者
((IWebHostEnvironment)html.ViewContext.HttpContext.RequestServices.GetService(typeof(IWebHostEnvironment))).WebRootPath
在这个answer你可以找到更多细节。
我也是推荐您使用此代码:
var path = Path.Combine(WebRootPath,"Views",s)
代替
var path = WebRootPath + "Views\\" + s
在所有 上运行代码操作系统 .
关于asp.net-core - 如何从助手内部获取 asp.net 核心中的 server.MapPath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38483962/