title: How do I customize ASP.Net Core model binding errors?
body: <p>I would like to return only standardized error responses from my Web API (Asp.net Core 2.1), but I can't seem to figure out how to handle model binding errors.</p>
  
  <p>The project is just created from the "ASP.NET Core Web Application" > "API" template. I've got a simple action defined as: </p>
  
  <pre><code>[Route("[controller]")]
  [ApiController]
  public class MyTestController : ControllerBase
  {
      [HttpGet("{id}")]
      public ActionResult&lt;TestModel&gt; Get(Guid id)
      {
          return new TestModel() { Greeting = "Hello World!" };
      }
  }
  
  public class TestModel
  {
      public string Greeting { get; set; }
  }
  </code></pre>
  
  <p>If I make a request to this action with an invalid Guid (eg, <code>https://localhost:44303/MyTest/asdf</code>), I get back the following response:</p>
  
  <pre><code>{
      "id": [
          "The value 'asdf' is not valid."
      ]
  }
  </code></pre>
  
  <p>I've got the following code in <code>Startup.Configure</code>:</p>
  
  <pre><code>public void Configure(IApplicationBuilder app, IHostingEnvironment env)
  {
      JsonErrorMiddleware.CreateSingleton(env);
  
      if (!env.IsDevelopment())
      {
          app.UseHsts();
      }
  
      app
          .UseHttpsRedirection()
          .UseStatusCodePages(async ctx =&gt; { await JsonErrorMiddleware.Instance.Invoke(ctx.HttpContext); })
          .UseExceptionHandler(new ExceptionHandlerOptions() { ExceptionHandler = JsonErrorMiddleware.Instance.Invoke })
          .UseMvc()
  }
  </code></pre>
  
  <p><code>JsonErrorMiddleware</code> is simply a class that converts errors to the correct shape I want to return and puts them into the response. It is not getting called at all for the model binding errors (no <code>Exception</code> is thrown and <code>UseStatusCodePages</code> is not called).</p>
  
  <p>How do I hook into the model binding to provide a standardized error response across all actions in my project?</p>
  
  <p>I've read a bunch of articles, but they all seem to either discuss global exception handling or validation errors.</p>