I am posting JSON data to API. If I post wrong data, catch block is not catching error. Controls stops at using (httpResponse = (HttpWebResponse)httpWebRequest.GetResponse()) this point and shows error. What wrong I am doing.
Following is my code,
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;
}
}