2

In ASP.NET Core with controllers I was able to customize the error response when a model binding error ocurred by adding the following in Program.cs:

builder.Services.Configure<ApiBehaviorOptions>(options =>
{
    options.InvalidModelStateResponseFactory = actionContext =>
    {
        var errors = actionContext.ModelState
            .Where(e => e.Value.Errors.Count > 0)
            .Select(e => new
            {
                Name = e.Key,
                Message = e.Value.Errors.First().ErrorMessage
            }).ToArray();

        return new BadRequestObjectResult(errors);
    };
});

This doesn't seem to be working with minimal API. How can I achieve the same results with Minimal API?

sanfalero
  • 372
  • 2
  • 18

1 Answers1

2

Minimal api does not support Model Binding, So you can't use InvalidModelStateResponseFactory in Minimal api.

Microsoft official documents are as follows

No support for model binding, i.e. IModelBinderProvider, IModelBinder. Support can be added with a custom binding shim.

No support for binding from forms. This includes binding IFormFile. We plan to add support for IFormFile in the future.

You can refer to this link to learn more details about the different between minimal api and controller api

Xinran Shen
  • 8,416
  • 2
  • 3
  • 12
  • If my answer help you resolve your issue, could you please accept as answer? Thanks. – Xinran Shen Mar 30 '22 at 16:03
  • My question was how can I achieve the same result in minimal API. This was helpful in understanding why model binding doesn't work in minimal APi, but doesn't solve the issue. – sanfalero Apr 03 '22 at 18:34