Quantcast
Channel: Brian Pedersen's Sitecore and .NET Blog
Viewing all articles
Browse latest Browse all 286

.NET Core Catch Model Binding Exceptions

$
0
0

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:


Viewing all articles
Browse latest Browse all 286

Trending Articles