C# 列出Json解析错误,检测部分对象Json格式错误-Aspnet Webapi
我有一节课C# 列出Json解析错误,检测部分对象Json格式错误-Aspnet Webapi,c#,json,asp.net-web-api,C#,Json,Asp.net Web Api,我有一节课 class Sample { public string str1; public string str2; public string str3; public string str4; public DateTime date1; public DateTime date2; } 我使用的是Aspnet Webapi Http Post方法,需要解析body 通常,如果正文的JSON格式有较大错误,例如开始时缺少括号: [ "st
class Sample
{
public string str1;
public string str2;
public string str3;
public string str4;
public DateTime date1;
public DateTime date2;
}
我使用的是Aspnet Webapi Http Post方法,需要解析body
通常,如果正文的JSON格式有较大错误,例如开始时缺少括号:
[
"str1": "32226","str2":"ABC","str3" :"91492","str4":"AC","date1":"1997-04-23T18:25:43",
"date2":"1997-04-23T18:25:43"
},
{"str1": "3226","str2":"ABF","str3" :"492","str4":"AB","date1":"1997-04-23T18:25:43","date2":"1997-04-23T18:25:43"
}
]
当使用[FromBody]List samples解析主体时,您将得到samples=null,因此您可以使用null来说明主体的json格式是错误的
但当我尝试创建属性的DateTime JSON格式错误时,例如下面第一个对象中的date2:
[
{"str1": "32226","str2":"ABC","str3" :"91492","str4":"AC","date1":"1997-04-23T18:25:43",
"date2":"1997-04-2325:43" -> date2 error datetime string
},
{"str1": "3226","str2":"ABF","str3" :"492","str4":"AB","date1":"1997-04-23T18:25:43","date2":"1997-04-23T18:25:43"
}
]
然后使用[FromBody]List samples进行解析,可以成功解析第二个Sample对象,并显示samples的List计数等于1
但是没有任何异常或信息表明第一个对象的JSON解析失败,如果两个对象都正确解析,那么样本数将为2
我尝试将DateTime类型更改为DateTime?,但是,这是相同的,只是第二个对象被解析,第一个对象被默默地忽略
有没有办法检测这种错误,即只有一些对象的JSON格式是错误的
我可以认为一个简单的方法是计算字符{present times,并与列表计数进行比较,如果{s count- 但是没有任何异常或信息可以告诉我第一个对象的JSON解析失败
是的,有一种方法可以查看JSON解析是否有错误
在您的应用程序中\u启动
只需执行以下操作
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.Error +=
delegate(object sender, ErrorEventArgs args)
{
File.WriteAllText(@"c:\\temp\\jsonerrortest.txt", args.ErrorContext.Error.Message);
};
}
更新
根据您的评论:
在执行过程中有什么方法可以判断吗?我想告诉post方法中解析的错误,并抛出一个异常,通知用户输入体是错误的
是的,有办法做到这一点,你必须截获你的消息与DelegatingHandler
如下所示:
public class MessageHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
string requestInfo = string.Empty;
requestInfo = string.Format("{0}:{1}", request.Method, request.RequestUri);
var requestMessage = await request.Content.ReadAsByteArrayAsync();
IncommingMessageAsync( requestInfo, requestMessage);
var response = await base.SendAsync(request, cancellationToken);
byte[] responseMessage;
if (response.IsSuccessStatusCode)
{
if (response.Content != null)
responseMessage = await response.Content.ReadAsByteArrayAsync();
else
responseMessage = Encoding.UTF8.GetBytes(response.ReasonPhrase);
}
else
responseMessage = Encoding.UTF8.GetBytes(response.ReasonPhrase);
OutgoingMessageAsync( requestInfo, responseMessage);
return response;
}
protected void IncommingMessageAsync(string requestInfo, byte[] message)
{
var obj =JObject.Parse(Convert.ToString(message));
}
protected void OutgoingMessageAsync( string requestInfo, byte[] message)
{
}
}
这将在出现解析错误时以详细模式引发异常
{
"Message": "An error has occurred.",
"ExceptionMessage": "Unexpected character encountered while parsing value: S. Path '', line 0, position 0.",
"ExceptionType": "Newtonsoft.Json.JsonReaderException",
"StackTrace": " à Newtonsoft.Json.JsonTextReader.ParseValue()\r\n à Newtonsoft.Json.JsonTextReader.Read()\r\n à Newtonsoft.Json.Linq.JObject.Load(JsonReader reader)\r\n à Newtonsoft.Json.Linq.JObject.Parse(String json)\r\n à MessageHandler.IncommingMessageAsync(String requestInfo, Byte[] message) dans c:\\tests\\WebApplication2\\WebApplication2\\MessageHandler.cs:ligne 45\r\n à MessageHandler.<SendAsync>d__0.MoveNext() dans c:\\tests\\WebApplication2\\WebApplication2\\MessageHandler.cs:ligne 21\r\n--- Fin de la trace de la pile à partir de l'emplacement précédent au niveau duquel l'exception a été levée ---\r\n à System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n à System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n à System.Web.Http.HttpServer.<SendAsync>d__0.MoveNext()"
}
注
出于安全考虑,永远不要这样做
改为创建自定义异常谢谢您的回答,我稍后会尝试。在执行逻辑代码期间有没有办法告诉用户?我想告诉post方法中解析的错误,以便我可以返回异常HttpResponseMessage,在输入正文出错时通知用户。
{
"Message": "An error has occurred.",
"ExceptionMessage": "Unexpected character encountered while parsing value: S. Path '', line 0, position 0.",
"ExceptionType": "Newtonsoft.Json.JsonReaderException",
"StackTrace": " à Newtonsoft.Json.JsonTextReader.ParseValue()\r\n à Newtonsoft.Json.JsonTextReader.Read()\r\n à Newtonsoft.Json.Linq.JObject.Load(JsonReader reader)\r\n à Newtonsoft.Json.Linq.JObject.Parse(String json)\r\n à MessageHandler.IncommingMessageAsync(String requestInfo, Byte[] message) dans c:\\tests\\WebApplication2\\WebApplication2\\MessageHandler.cs:ligne 45\r\n à MessageHandler.<SendAsync>d__0.MoveNext() dans c:\\tests\\WebApplication2\\WebApplication2\\MessageHandler.cs:ligne 21\r\n--- Fin de la trace de la pile à partir de l'emplacement précédent au niveau duquel l'exception a été levée ---\r\n à System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n à System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n à System.Web.Http.HttpServer.<SendAsync>d__0.MoveNext()"
}