I have a site where users can post links with images from another websites. Problem is some times this links a broken and don't contain an image, and I see a broken image instead of image on my web site.
How can I check does the link to other website contains an image or not?
CodePudding user response:
You can send a GET request to the image url, if the response status code is 200 then the image was found, if 404 not found.
using var httpClient = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Get, "link-to-image");
var response = httpClient.Send(request); // Exist SendAsync version
var statusCode = response.StatusCode; // 200 image exist, 404 not exist
CodePudding user response:
Guess this code can help. It's a bit harder than the previous author's one, sorry
string imageUrl = "http://example.com/image.jpg";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(imageUrl);
request.Method = "HEAD";
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode == HttpStatusCode.OK)
{
//Image exists
}
else
{
//Image does not exist
}
}