I am hitting a web services that returns its errors as a json. How can I interpret these errors when I am using a web client? I want to be able to pass these onto my users so they no the errors they are getting.
{ "success": false, "errors": [
{
"propertyName": "Reference",
"reason": "'Reference' must not be empty."
},
{
"propertyName": "Reference",
"reason": "'Reference' should not be empty."
},
{
"propertyName": "Key",
"reason": "'Key' must be between 10 and 15 characters. You entered 3 characters."
},
{
"propertyName": "Key",
"reason": "Key does not start with zero: 123."
} ], "warnings": [], "information": []
public void TransferToSlate(string json, string url)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
public void TransferToSlate(string json, string url)
{
try {
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
catch (WebException ex){
var resp = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
dynamic obj = JsonConvert.DeserializeObject(resp);
var messageFromServer = obj.error.message;
}
public class ErrorMessage
{
public string PropertyName { get; set; }
public string Reason { get; set; }
public override string ToString()
{
return string.IsNullOrWhiteSpace(PropertyName)
? Reason
: string.Format("{0} : {1}", PropertyName, Reason);
}
}
You can read the response from the WebException
:
try
{
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
catch(WebException ex)
{
var httpResponse = ex.Response as HttpWebResponse;
if (httpResponse != null)
{
// process the response
}
}