Skip to content

Instantly share code, notes, and snippets.

@x789
Created March 9, 2023 16:21
Show Gist options
  • Save x789/f8459131f6fef7e1de29dd5f38cd52a8 to your computer and use it in GitHub Desktop.
Save x789/f8459131f6fef7e1de29dd5f38cd52a8 to your computer and use it in GitHub Desktop.
ASP.NET Custom Response on Model-Validation Error
using System;
using Microsoft.AspNetCore.Mvc;
public class InvalidModelStateResponseFactory
{
public static ProblemDetails Create(ActionContext _) => new();
public class ProblemDetails : IActionResult
{
public Task ExecuteResultAsync(ActionContext context)
{
context.HttpContext.Response.StatusCode = 418;
context.HttpContext.Response.Headers.Add("custom-header", "custom-value");
return Task.CompletedTask;
}
}
}
builder.Services.AddControllers().ConfigureApiBehaviorOptions(opt =>
{
opt.SuppressMapClientErrors = true; // Automatic problem-details generation must be disabled to activate the custom factory.
opt.InvalidModelStateResponseFactory = InvalidModelStateResponseFactory.Create;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment