.NET Core Catch Model Binding Exceptions

In .NET Core, if you create an API project, and you have an controller receiving an object you defined yourself, the controller will not be called if you use the wrong model, or if the model is not in a correct JSON/XML format.

This means that you cannot catch the exception in your own try/catch block, which is annoying if you would like to log the exception in your own log file, or to your own Application Insights instance.

To catch model binding exceptions, you need to configure the ApiBehaviorOptions in your ConfigureServices(IServiceCollection services) method.

STEP 1: CALL services.Configure<ApiBehaviorOptions>:

I have made a private method in my Startup.cs file:

private void ConfigureModelBindingExceptionHandling(IServiceCollection services)
{
  services.Configure&lt;ApiBehaviorOptions&gt;(options =>
  {
    options.InvalidModelStateResponseFactory = actionContext =>
    {
      ValidationProblemDetails error = actionContext.ModelState
          .Where(e => e.Value.Errors.Count > 0)
          .Select(e => new ValidationProblemDetails(actionContext.ModelState)).FirstOrDefault();

      // Here you can add logging to you log file or to your Application Insights.
	  // For example, using Serilog:
	  // Log.Error($"{{@RequestPath}} received invalid message format: {{@Exception}}", 
	  //   actionContext.HttpContext.Request.Path.Value, 
	  //   error.Errors.Values);
      return new BadRequestObjectResult(error);
    };
  });
}

STEP 2: CALL THE METHOD AFTER LOG AND/OR APPLICATION INSIGHTS HAVE BEEN INSTANTIATED:

Sequence is important. In the public void ConfigureServices(IServiceCollection services) method, after you have instantiated logging, Application Insights, or whatever you use. Then call the new method:

public void ConfigureServices(IServiceCollection services)
{
  // Add logging, Application Insights, Controllers, ...
  ...
  ...
  // Add exception logging on model binding exceptions
  ConfigureModelBindingExceptionHandling(services, telemetryClient);
  ...
  ...
}

MORE TO READ:

About briancaos

Developer at Pentia A/S since 2003. Have developed Web Applications using Sitecore Since Sitecore 4.1.
This entry was posted in .NET Core, c#, Microsoft Azure and tagged , , . Bookmark the permalink.

1 Response to .NET Core Catch Model Binding Exceptions

  1. Pingback: .NET Core Api – Catch exceptions using a middleware | Brian Pedersen's Sitecore and .NET Blog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.