AspNetCore在TagHelper中获取wwwroot的路径
本文关键字:wwwroot 路径 获取 TagHelper AspNetCore | 更新日期: 2023-09-27 18:12:49
我尝试创建一个TagHelper来检查图像是否存在,如果不存在则替换默认图像的路径。
不幸的是,我在标签帮助器中映射"~"符号时遇到了问题。
例如。我的图像src包含"~'images'image1.png"。现在我想检查这个文件是否存在,如果不存在,就用标签属性中的另一个文件替换它。我被困在映射"~"到我的应用程序的wwwroot。
这是我实际得到的:
[HtmlTargetElement("img", TagStructure = TagStructure.WithoutEndTag)]
public class ImageTagHelper : TagHelper
{
public ImageTagHelper(IHostingEnvironment environment)
{
this._env = environment;
}
private IHostingEnvironment _env;
public string DefaultImageSrc { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
// urlHelper.ActionContext.HttpContext.
//var env = ViewContext.HttpContext.ApplicationServices.GetService(typeof(IHostingEnvironment)) as IHostingEnvironment;
string imgPath = context.AllAttributes["src"].Value.ToString();
if (!File.Exists(_env.WebRootPath + imgPath)) {
output.Attributes.SetAttribute("src", _env.WebRootPath + DefaultImageSrc);
}
}
}
你应该接受IUrlHelperFactor和IActionContextAccessor的构造函数依赖,这将使你能够获得一个IUrlHelper,它可以通过"~/"语法从wwwroot解析url
public ImageTagHelper(
IUrlHelperFactory urlHelperFactory,
IActionContextAccessor actionContextAccesor,)
{
this.urlHelperFactory = urlHelperFactory;
this.actionContextAccesor = actionContextAccesor;
}
private IUrlHelperFactory urlHelperFactory;
private IActionContextAccessor actionContextAccesor;
public override void Process(TagHelperContext context, TagHelperOutput output)
{
var urlHelper = urlHelperFactory.GetUrlHelper(actionContextAccesor.ActionContext);
var myUrl = urlHelper.Content("~/somefilebelowwwwroot");
...
}
可以看到我在PagerTagHelper中做了
需要在Startup.cs
的ConfigureServices方法中添加一个您需要添加以下行:
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
然后这个就行了:
[HtmlTargetElement("img", TagStructure = TagStructure.WithoutEndTag)]
public class ImageTagHelper : TagHelper
{
public ImageTagHelper(IUrlHelperFactory urlHelperFactory,
IActionContextAccessor actionContextAccessor,
IHostingEnvironment environment)
{
_urlHelperFactory = urlHelperFactory;
_actionContextAccessor = actionContextAccessor;
_env = environment;
}
private IUrlHelperFactory _urlHelperFactory;
private IActionContextAccessor _actionContextAccessor;
private IHostingEnvironment _env;
public string DefaultImageSrc { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
string imgPath = context.AllAttributes["src"].Value.ToString();
IUrlHelper urlHelper = _urlHelperFactory.GetUrlHelper(_actionContextAccessor.ActionContext);
if (!imgPath.StartsWith("data:"))
{
if (!File.Exists(_env.WebRootPath + urlHelper.Content(imgPath)))
{
if (DefaultImageSrc != null)
{
output.Attributes.SetAttribute("src", urlHelper.Content(DefaultImageSrc));
}
}
}
}
}