Search code examples
restasp.net-corejson.netasp.net-core-mvc

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


Solution

  • 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...
                  };
            });