gpt4 book ai didi

asp.net-mvc - 如何在 razor 中为 .net core 2.0 mvc 映射路径?

转载 作者:行者123 更新时间:2023-12-02 21:52:10 24 4
gpt4 key购买 nike

我正在尝试将布局页面转换为.net core 2.0。不幸的是,在 razor Server.MapPath 中不再可用。

我正在尝试在 .cshtml 页面中找到

的等效内容
<div style="height: 0px; width: 0px; position: absolute; visibility: hidden;">
@Html.Raw(System.IO.File.ReadAllText(Server.MapPath("~/Content/images/svg-defs.svg")))
</div>

最佳答案

在 ASP.NET Core 中,您可以使用 IHostingEnvironment 服务来访问 Web 应用程序的某些路径。

这个对象有两个有趣的属性:

  • ContentRootPath:应用程序基本路径的路径(您通常可以在其中找到 appsettings.json、Program.cs 等
  • WebRootPath:/wwwroot 目录的路径,这就是您要查找的目录。

要访问 IHostingEnvironment 服务,只需将其注入(inject) Controller 的构造函数中,并用一个字段保留它。

public class HomeController : Controller
{
private IHostingEnvironment _env;

public HomeController(IHostingEnvironment env)
{
_env = env;
}
}

现在,在此 Controller 的操作方法中,您可以使用 System.IO.Path.Combine 和 WebRootPath 属性构造文件的物理路径。

public IActionResult Index()
{
ViewBag.FilePath = Path.Combine(_env.WebRootPath, @"Content\images\svg-defs.svg");
return View();
}

在此示例中,我将生成的路径添加到 ViewBag 中,以便轻松地将其显示在索引 View 中:

<h2>Index View</h2>

<p>Filepath: @ViewBag.FilePath</p>

这将打印类似于 C:\MySite\wwwroot\Content\images\svg-defs.svg

的内容

关于asp.net-mvc - 如何在 razor 中为 .net core 2.0 mvc 映射路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47893477/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com