How to log ASP.NET Core input JSON serialization e

2020-08-17 07:49发布

问题:

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

回答1:

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