简体   繁体   中英

asp:Image display image or not

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.

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 .

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 (eg 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.

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 !!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM