最簡單的方法是使用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);
}
}
}
然後在您的視圖中,您可以使用以下内容制作網址:
" />
編輯:正如吉姆指出的那樣,我還沒有真正解決尺寸問題.我個人使用自動大小請求管理/大小這是另一個故事,但如果你擔心檔案夾/大小隻是傳遞資訊來建構路徑.如下:
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);
}
}
}
然後在您的視圖中,您可以使用以下内容制作網址:
" />
如果檔案夾是一個固定的集合,建議使用Enum以獲得更好的程式設計控制,但是為了快速而讨厭的方法,如果檔案夾是db生成的話,不能僅僅使用字元串.