【发布时间】:2016-10-12 23:41:12
【问题描述】:
我尝试创建一个 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);
}
}
}
【问题讨论】:
标签: c# asp.net-core