简体   繁体   中英

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.

But sometimes, end user passes invalid data or junk data due to which my object returns as a 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:

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.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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