简体   繁体   中英

Web Response status code

I have this simple function to get HTML pages and return it as a string; though sometimes I get a 404. How can I only return the HTML string only if the request was successful, and return something like BadRequest when it's a 404 or any other error status code?

public static string GetPageHTML(string link)
{
    using (WebClient client= new WebClient())
    {
        return client.DownloadString(link);
    }
}

You could catch the WebException:

public static string GetPageHTML(string link)
{
    try
    {
        using (WebClient client = new WebClient())
        {
            return client.DownloadString(link);
        }
    }
    catch (WebException ex)
    {
        var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
        return "An error occurred, status code: " + statusCode;
    }
}

Of course it would be more appropriate to catch this exception in the calling code and not even attempt to parse the html instead of putting the try/catch in the function itself.

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