I am using asp:image field to get an image from different urls. I use the imageurl to set the image string from the remote website(ex: http://www.google.com/favicon.ico), the question is how can I tell if the image exist or not? that mean that the Url of the image is valid.
3 Answers
You can validate if a URI is valid using the Uri.TryCreate method.
You shouldn't be checking whether the image exists in your ASP.Net application. It is the job of the browser to download the image. You can add javascript to allow the browser to replace the missing image with a default image, as described in this question.

- 1
- 1

- 10,358
- 1
- 26
- 46
You can't do this by using the asp:Image control alone. However, with a little extra work it would be possible to use a ASHX handler to make a programmatical HttpRequest
for the image (e.g. using the image on the querystring). If the HttpRequest
succeeds, you can then stream the image to the response.
If the HttpRequest
returns a 404 status, then you can serve another predefined image instead.
However, this is like using a sledgehammer to crack a nut and should not be used extensively throughout a site as it could potentially create a significant load - essentially, you are asking the server (not the user's browser) to download the image. Also it could be a potential XSS security risk if not implemented carefully.
It would be fine for individual cases, specifically when you actually need to retain the requested image locally. Any images requested should be written to disk so that future requests can serve the previously retained images.
Obviously, Javascript is a solution too but I mention the above as a possibility, depending on the requirements.

- 10,310
- 4
- 38
- 66
class MyClient : WebClient
{
public bool HeadOnly { get; set; }
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest req = base.GetWebRequest(address);
if (HeadOnly && req.Method == "GET")
{
req.Method = "HEAD";
}
return req;
}
}
private bool headOnly;
public bool HeadOnly {
get {return headOnly;}
set {headOnly = value;}
}
using(var client = new MyClient()) {
client.HeadOnly = true;
// fine, no content downloaded
string s1 = client.DownloadString("http://google.com");
// throws 404
string s2 = client.DownloadString("http://google.com/silly");
}
try this one !!!

- 2,205
- 16
- 16