Web响应状态码 [英] Web Response status code

查看:107
本文介绍了Web响应状态码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个简单的函数来获取HTML页面并将其作为字符串返回;尽管有时我会收到404.如何仅在请求成功的情况下返回HTML字符串,而在返回404或任何其他错误状态代码时返回类似BadRequest的内容呢?

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);
    }
}

推荐答案

您可以捕获WebException:

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;
    }
}

当然,更合适的是在调用代码中捕获此异常,而不是尝试解析html,而不是将try/catch放在函数本身中.

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.

这篇关于Web响应状态码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆