In an ASP.NET Core [ApiController], how do you customise the automatic invalid-ModelState response with InvalidModelStateResponseFactory, and what can that factory not change?
answer
- ConfigureApiBehaviorOptions on AddControllers
- Func<ActionContext, IActionResult>
- keep ProblemDetailsFactory for the shape
- ModelStateInvalidFilter at order -2000
- SuppressModelStateInvalidFilter to opt out
basics
~10 sSet ApiBehaviorOptions.InvalidModelStateResponseFactory through AddControllers().ConfigureApiBehaviorOptions; it receives the ActionContext and returns the IActionResult sent instead of running the action. It only affects [ApiController] controllers and runs before your ordinary action filters.
solid answer
~40 sUnder `[ApiController]`, a `ModelStateInvalidFilter` (order -2000) checks `ModelState.IsValid` before the action and, when it is false, returns whatever `ApiBehaviorOptions.InvalidModelStateResponseFactory` produces. The default builds validation problem details with `ProblemDetailsFactory` and wraps them in a `BadRequestObjectResult`. You replace it with `builder.Services.AddControllers().ConfigureApiBehaviorOptions(o => o.InvalidModelStateResponseFactory = ctx => ...)`. The `ActionContext` gives you `HttpContext`, `ModelState` and the action descriptor, so you can log the failed keys, switch to 422 by passing `statusCode: 422` to `CreateValidationProblemDetails`, or add a trace id while keeping the standard shape. It cannot touch controllers without `[ApiController]`, Minimal API handlers, or exceptions. If you need to see invalid state in your own filter or action, set `SuppressModelStateInvalidFilter = true` and handle `IsValid` yourself.
go deeper
Know that [ApiController] returns 400 automatically for invalid models and that this response can be customised in startup configuration.
Explain ConfigureApiBehaviorOptions, the factory's ActionContext input, and how SuppressModelStateInvalidFilter hands the check back to actions.
Customise status and logging without breaking the problem details contract, mind filter order -2000, and keep personal data out of logs.
Standardise one validation error contract across controllers, Minimal APIs and exceptions, and decide where each surface plugs into it.
## Where the automatic 400 comes from When a controller (or its assembly) carries `[ApiController]`, MVC adds a **`ModelStateInvalidFilter`** to each action. It is an action filter with order **-2000**, so it runs before filters at the default order 0. Its whole job: 1. If no earlier filter has set a result and `ModelState.IsValid` is false, 2. call `ApiBehaviorOptions.InvalidModelStateResponseFactory(context)`, 3. and use the returned `IActionResult` instead of running the action. The default factory asks the registered `ProblemDetailsFactory` for `CreateValidationProblemDetails(httpContext, modelState)` and returns it as a `BadRequestObjectResult` with the content types `application/problem+json` and `application/problem+xml`. The exact body shape is a ProblemDetails topic; here the point is the hook. ## Replacing the factory ```csharp builder.Services.AddControllers() .ConfigureApiBehaviorOptions(options => { options.InvalidModelStateResponseFactory = context => { var logger = context.HttpContext.RequestServices .GetRequiredService<ILogger<MembershipsController>>(); logger.LogWarning("Sign-up rejected: {Fields}", string.Join(",", context.ModelState.Keys)); var factory = context.HttpContext.RequestServices .GetRequiredService<ProblemDetailsFactory>(); var problem = factory.CreateValidationProblemDetails( context.HttpContext, context.ModelState, statusCode: 422); return new UnprocessableEntityObjectResult(problem); }; }); ``` Things that make a factory good: - **Reuse `ProblemDetailsFactory`.** It fills `type`, `title`, `status`, the `errors` dictionary and a trace id consistently with the rest of the API. - **Keep it cheap and side-effect free.** It runs for every invalid request; logging keys is fine, calling other services is not. - **Do not log values.** `ModelState` holds attempted values; a sign-up model carries emails and phone numbers. - **Resolve services from `context.HttpContext.RequestServices`.** The factory is one delegate configured at startup and shared by every request. ## What the factory cannot do | You want to | Factory helps? | Do instead | |---|---|---| | Change status or body for `[ApiController]` validation failures | yes | the factory | | Affect a controller without `[ApiController]` | no | check `ModelState.IsValid` in the action or a filter | | Change Minimal API validation responses | no | the Minimal API validation pipeline | | Shape responses for exceptions | no | `IExceptionHandler` and the exception handler middleware | | Let your own action filter see invalid state first | no, it runs at -2000 | give the filter a lower order, or suppress the built-in filter | | Skip the check for one action | no | set `SuppressModelStateInvalidFilter = true` and check where needed | ## Turning the filter off `ApiBehaviorOptions.SuppressModelStateInvalidFilter = true` removes the automatic response for every `[ApiController]` action. Then each action, or a filter of your own, must check `ModelState.IsValid` and can return `ValidationProblem()` from `ControllerBase`, which builds the same validation problem details through `ProblemDetailsFactory`. Teams do this when some endpoints must accept partially valid input, or when validation outcomes feed a custom workflow. Two configuration mistakes to avoid: - Setting `InvalidModelStateResponseFactory = null` while the filter is still active makes MVC throw an `ArgumentException` when it creates the filter. - Registering a custom factory and also suppressing the filter means the framework never calls your delegate; `ValidationProblem()` goes straight to `ProblemDetailsFactory`, not through `InvalidModelStateResponseFactory`. ## What interviewers listen for - That the 400 is produced by an action filter, and where it sits in filter order. - The `ConfigureApiBehaviorOptions` hook and the `ActionContext` it receives. - Reusing `ProblemDetailsFactory` instead of inventing a new error shape. - The limits: `[ApiController]` only, not exceptions, not Minimal APIs.
- Your custom action filter needs to log invalid sign-ups but never runs for them; why?`ModelStateInvalidFilter` runs at order -2000 and sets a result before filters at the default order 0 execute, which short-circuits the rest of the action pipeline. Give your filter an order below -2000, move the logging into `InvalidModelStateResponseFactory`, or set `SuppressModelStateInvalidFilter = true` and handle invalid state yourself.
- How do you return 422 instead of 400 while keeping the standard validation body?In the factory, call `ProblemDetailsFactory.CreateValidationProblemDetails(context.HttpContext, context.ModelState, statusCode: 422)` and return it in an `UnprocessableEntityObjectResult` (or an `ObjectResult` with `StatusCode = 422`). The body keeps the `errors` dictionary and trace id; only the status changes.
- InvalidModelStateResponseFactory also shapes responses for unhandled exceptions.
- The factory runs for every controller, with or without [ApiController].
- Your own default-order action filter sees the invalid ModelState before the automatic 400.
- Setting the factory to null is the way to disable the automatic 400.
- The factory is the right place to log every attempted value for debugging.