Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to log ASP.NET Core input JSON serialization errors

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..

like image 986
dstr Avatar asked Oct 26 '17 07:10

dstr


People also ask

What is Jsonserializersettings?

Specifies the settings on a JsonSerializer object. Newtonsoft.Json.

How do I deserialize a JSON string to an object in C#?

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.

What is serialization and deserialization of JSON in C#?

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.


1 Answers

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...
              };
        });
like image 194
dstr Avatar answered Sep 18 '22 11:09

dstr