简体   繁体   English

WebAPI-接受无效的JSON

[英]WebAPI - to accept invalid JSON

I have developed WebAPI with one class in which I can pass json and my class auto fills all values. 我已经用一个类开发了WebAPI,可以在其中传递json,并且我的类会自动填充所有值。

But sometimes, end user passes invalid data or junk data due to which my object returns as a null. 但是有时,最终用户传递无效数据或垃圾数据,由于这些原因,我的对象返回为null。

I need to record each requests regardless valid or invalid for my records. 我需要记录每个请求,无论对我的记录有效还是无效。

How can I do that? 我怎样才能做到这一点?

If you provide any code of some your implementation the answer may be more accurate. 如果您提供某些实现的代码,则答案可能会更准确。

Generally if you have a class to serialize / deserialize in JSON one way may be: 通常,如果您有一个要在JSON中序列化/反序列化的类,一种方法可能是:

public class Response
{
    public bool success { get; set; }
    public string data { get; set; } 
    public string timestamp { get; set; }
    ...
}

Using Newtonsoft JSON serializer to Deserialize a json string to it's corresponding class object. 使用Newtonsoft JSON序列化程序将json字符串反序列化为其对应的类对象。

try
{
    var jsonInput = "{success:true,data:'hello', timestamp:'123123123'}"; /*Request at you API*/
    Response response = Newtonsoft.Json.JsonConvert.DeserializeObject<Response>(jsonInput);
}
catch(Exception)
{
    // handle here bad request
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM