0
我張貼JSON數據API。如果我張貼錯誤的數據,catch
塊沒有捕獲錯誤。控制停止在using (httpResponse = (HttpWebResponse)httpWebRequest.GetResponse())
這一點,並顯示錯誤。我在做什麼錯。 以下是我的代碼,錯誤HttpWebRequest的異常處理
try
{
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
var httpWebRequest = (HttpWebRequest)WebRequest.Create("ipaddress");
httpWebRequest.Credentials = new NetworkCredential("", "");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string name = objTSPost.name;
string servicetype = objTSPost.service_type;
string json = "{\"name\":\"VMR_" + name + "\"," +
"\"service_type\":\"" + servicetype + "\"}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
using (httpResponse = (HttpWebResponse)httpWebRequest.GetResponse())
{
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
string str = "{\"name\":\"VMR_" + objTSPost.name + "\"," +
"\"service_type\":\"" + objTSPost.service_type + "\"}";
var data = JsonConvert.DeserializeObject<TSGetRootObject>(str);
data.status = ((HttpWebResponse)httpResponse).StatusDescription;
return data;
}
}
catch (WebException ex)
{
objTSPost.status = ex.Message;
return objTSPost;
}
}
你可以發佈你所得到的是錯誤的一些細節?消息,異常的類型? –
如果catch沒有捕獲,則使用更通用的Exception而不是WebException。 – sachin
您只捕獲webexception類型的例外。它可能會拋出一些其他類型的異常,這就是爲什麼它沒有被捕獲。我建議,你應該添加另一個泛型類型爲「Exception」的catch塊。像這樣的東西catch(Exception ex) {objTSPost.status = ex.Message; return objTSPost; } – Majid