We have ASP.NET Core application which we use as a REST api. Methods use [FromBody]MyClass param
as input. Problem is if the client sends an invalid JSON string the input
value becomes null due to JSON serialization errors. Is there a way to log such errors?
Edit: I'm looking for application-wide solution not per-method..
Specifies the settings on a JsonSerializer object. Newtonsoft.Json.
A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.
Json structure is made up with {}, [], comma, colon and double quotation marks and it includes the following data types: Object, Number, Boolean, String, and Array. Serialize means convert an object instance to an XML document. Deserialize means convert an XML document into an object instance.
I've solved this with adding an error handler in Startup.cs:
services.AddMvc()
.AddJsonOptions(options => {
options.SerializerSettings.Error = (object sender, Newtonsoft.Json.Serialization.ErrorEventArgs args) =>
{
//Log args.ErrorContext.Error details...
};
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With