我正在为SiteScope编写诊断页面,我们需要测试的一个区域是,是否可以从Web服务器访问文件/媒体资产的连接.我认为我可以这样做的一种方法是通过代码加载图像并测试以查看IIS状态消息是否为200.
所以基本上我应该能够在站点内导航到这样的文件夹:/media/1/image.jpg并查看它是否返回200 ...如果不抛出异常.
我正在努力弄清楚如何编写这段代码.
任何帮助是极大的赞赏.
谢谢
只需使用HEAD.如果您不需要,无需下载整个图像.这里有一些样板代码.
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("url"); request.Method = "HEAD"; bool exists; try { request.GetResponse(); exists = true; } catch { exists = false; }
您可能还想检查是否有一个OK状态代码(即HTTP 200),并且响应对象中的mime类型与您期望的匹配.你可以沿着这条线延伸
public bool doesImageExistRemotely(string uriToImage, string mimeType) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uriToImage); request.Method = "HEAD"; try { HttpWebResponse response = (HttpWebResponse)request.GetResponse(); if (response.StatusCode == HttpStatusCode.OK && response.ContentType == mimeType) { return true; } else { return false; } } catch { return false; } }
您必须处置HTTPWebResponse对象,否则您将遇到问题,因为我有...
public bool DoesImageExistRemotely(string uriToImage) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uriToImage); request.Method = "HEAD"; try { using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { if (response.StatusCode == HttpStatusCode.OK) { return true; } else { return false; } } } catch (WebException) { return false; } catch { return false; } }
我之前使用过这样的东西,但可能有更好的方法:
try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://somewhere/picture.jpg"); request.Credentials = System.Net.CredentialCache.DefaultCredentials; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); myImg.ImageUrl = "http://somewhere/picture.jpg"; } catch (Exception ex) { // image doesn't exist, set to default picture myImg.ImageUrl = "http://somewhere/default.jpg"; }