在我的asp.net网站上,我正在动态构建某些页面.我从服务器加载了某些图像.如果图像不存在,那么我需要加载默认图像.
到目前为止,我一直在检查网址是否有效,如果是,那么我知道图像存在.如果网址无效,那么我知道在我的代码中提供我的默认图片.为此,我做到了这一点:
//returns true if the url actually exists
//however, this will ALWAYS throw an exception if it exists, so beware the debugger.
public static bool IsValidUrl(string url) {
HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(url);
httpReq.AllowAutoRedirect = false;
httpReq.Method = "HEAD";
httpReq.KeepAlive = false;
httpReq.Timeout = 2000;
HttpWebResponse httpRes = default(HttpWebResponse);
bool exists = false;
try {
httpRes = (HttpWebResponse)httpReq.GetResponse();
if (httpRes.StatusCode == HttpStatusCode.OK) {
exists = true;
}
} catch {
}
return exists;
}
Run Code Online (Sandbox Code Playgroud)
但这并不是一个很好的做事方式,我不喜欢像那样证明这个例外.此外,如果我添加新图像,服务器不会认为新图像是有效的网址,直到某个时间过去(或我在IIS中重新启动网站) - 这是导致我寻找另一种方法的bugger.
有没有更好的方法来提供默认图像,以防我选择的图像不存在?
如果您可以使用客户端解决方案,这可能适合您:
<img src="fakesrc" onerror="setDefaultImage(this);" />
Run Code Online (Sandbox Code Playgroud)
功能:
function setDefaultImage(img)
{
//set default.
img.src="https://www.google.com/images/srpr/logo11w.png";
}
Run Code Online (Sandbox Code Playgroud)
img将尝试从其原始src属性加载,onerror如果图像不存在,它将触发事件.该setDefaultImage()方法将图像设置为默认图像.
http://jsfiddle.net/Q64hn/
编辑:
如果文件在您的服务器中,您可以让文件系统处理:
public static bool IsValidUrl(string url) {
return System.IO.File.Exists(HttpContext.Current.Request.MapPath(url));
}
Run Code Online (Sandbox Code Playgroud)
你可以这样称呼它:
protected void Page_Load(object sender, EventArgs e)
{
bool x = IsValidUrl(ResolveUrl("~/Default.aspx"));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1382 次 |
| 最近记录: |