我尝试创建一个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);
}
}
}
Run Code Online (Sandbox Code Playgroud)