簡體   English   中英

Web響應狀態代碼

[英]Web Response status code

我有這個簡單的函數來獲取HTML頁面並將其作為字符串返回; 雖然有時我得到404.如果請求成功,我怎么才能返回HTML字符串,當它是404或任何其他錯誤狀態代碼時返回BadRequest之類的東西?

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

您可以捕獲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放在函數本身中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM