我如何检索基于json的错误,而不是标准.net
本文关键字:错误 net 标准 json 何检索 检索 | 更新日期: 2023-09-27 18:14:35
我正在击中一个web服务,返回其错误作为json。当我使用web客户端时,我如何解释这些错误?我希望能够把这些传递给我的用户,这样他们就不会得到错误。
{"success": false, "errors": [
]{
"propertyName":"引用",
"reason": " Reference "不能为空。"
},
{
"propertyName":"引用",
"reason": " Reference "不应该是空的。"
},{"propertyName":"关键",
"reason": "'Key'必须在10到15个字符之间。您输入了3个字符。"
},{"propertyName":"关键",
"reason": "Key不以0开头:123。"}], "warnings": [], "information": []
这就是我调用第三方api的方式,但当我击中这一行时,我得到了一个标准的。net错误抛出我的问题是我如何才能得到上面json的值返回
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
屏幕截图,因为我不能上传
https://snag.gy/Itoy02.jpgpublic 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();
}
}
编辑2 我已经尝试了以下,它让我更进一步,但不是错误
内的两个列表属性的下降。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);
}
}
编辑3
我在这里尝试了以下内容,但当我没有时,它只是返回null,它应该在我的第一篇文章中填充json中的bleow错误。
catch (WebException ex){
var resp = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
ErrorMessage error = JsonConvert.DeserializeObject<ErrorMessage>(resp);
var fieldinformation = error.PropertyName.ToString();
var messageFromServer = error.Reason.ToString();
}
您可以读取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
}
}