最简单的方法是使用 html 助手。请注意在显示图像文件名之前检查文件系统的额外性能损失。不过,点击量很小,因此除非您获得非常高的流量,否则您不会注意到任何问题。然后您可以实现某种缓存,以便应用程序“知道”文件是否存在。
您可以为此使用自定义 html 帮助程序
public static class ImageHtmlHelpers
{
public static string ImageUrlFor(this HtmlHelper helper, string contentUrl)
{
// Put some caching logic here if you want it to perform better
UrlHelper urlHelper = new UrlHelper(helper.ViewContext.RequestContext);
if (!File.Exists(helper.ViewContext.HttpContext.Server.MapPath(contentUrl)))
{
return urlHelper.Content("~/content/images/none.png");
}
else
{
return urlHelper.Content(contentUrl);
}
}
}
然后在您看来,您可以使用以下方法制作网址:
<img src="<% Html.ImageUrlFor("~/content/images/myfolder/myimage.jpg"); %>" />
编辑: 正如吉姆指出的,我还没有真正解决尺寸问题。我个人使用自动大小请求管理/大小,这是另一回事,但如果您担心文件夹/大小,只需传递该信息以构建路径。如下:
public static class ImageHtmlHelpers
{
public static string ImageUrlFor(this HtmlHelper helper, string imageFilename, ImageSizeFolderEnum imageSizeFolder)
{
UrlHelper urlHelper = new UrlHelper(helper.ViewContext.RequestContext);
string contentUrl = String.Format("~/content/userimages/{0}/{1}", imageSizeFolder, imageFilename);
if (!File.Exists(helper.ViewContext.HttpContext.Server.MapPath(contentUrl)))
{
return urlHelper.Content(String.Format("~/content/userimages/{0}/none.png", imageSizeFolder));
}
else
{
return urlHelper.Content(contentUrl);
}
}
}
然后在您看来,您可以使用以下方法制作网址:
<img src="<% Html.ImageUrlFor("myimage.jpg", ImageSizeFolderEnum.Small); %>" />
如果文件夹是固定集,则建议使用 Enum 进行更好的编程控制,但是对于快速而讨厌的方法,这不是为什么如果文件夹是 db 生成的等,您不能只使用字符串的原因。