![](/img/trans.png)
[英]Using a WebClient and C#, how do I get returned data even when the response is (400) Bad Request?
[英]How to display optional fields in response when using C# WebClient and getting exceptions?
我正在使用WebClient對服務器進行POST,如下所示:
string URI = "http://mydomain.com/foo";
string myParameters =
"&token=1234" +
"&text=" + HttpUtility.UrlEncode(someVariable);
using (WebClient wc = new WebClient())
{
try
{
wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
string HtmlResult = wc.UploadString(URI, myParameters);
}
catch (WebException e)
{
return e.Message;
}
}
有時我會因HTTP 403(禁止)而引發異常。 在這些情況下,我想知道確切原因。 深入研究我正在調用的服務,它被記錄下來,它將選擇性地返回errorDetail
字段,如下所示:
"code": 403,
"errorType": "not_authorized",
"errorDetail": "Can reply on a checkin at most once."
但是,當我在Visual Studio中逐步執行代碼時,看不到如何獲取errorDetail
字段。 它不apepar是部分WebException
。
有沒有一種方法可以讓我顯示,例如:
return e.Message + " -- " + e.errorDetail
?
errorDetail
不是HTTP規范的一部分,因此WebClient
對此一無所知。 出於同樣的原因,您不會在BCL中的任何位置找到它。
您可能想要的是響應正文,以便您可以對其進行解析(也許是JSON?您的數據看起來像這樣)。
您可以從WebException.Response
獲取響應對象。 像平時閱讀響應一樣閱讀它。
請注意,如果沒有響應(例如,由於網絡錯誤),則此屬性可能為null。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.