Created
March 9, 2023 16:21
-
-
Save x789/f8459131f6fef7e1de29dd5f38cd52a8 to your computer and use it in GitHub Desktop.
ASP.NET Custom Response on Model-Validation Error
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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