我尝试创建一个用于检查图像是否存在的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);
}
}
}
答案 0 :(得分:5)
您应该对IUrlHelperFactor和IActionContextAccessor采用构造函数依赖,这将使您能够获得可以使用“〜/”语法从wwwroot解析URL的IUrlHelper
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
中这样做了答案 1 :(得分:4)
它需要在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));
}
}
}
}
}