Created
February 27, 2021 07:46
-
-
Save Redouane64/e0f21c0cc7b2efe42af653e8491e140d to your computer and use it in GitHub Desktop.
AspNet Web API Invalid Model State Response Configuration
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 Microsoft.AspNetCore.Http; | |
| using Microsoft.AspNetCore.Mvc; | |
| using Microsoft.AspNetCore.Mvc.Filters; | |
| using Microsoft.AspNetCore.Mvc.Infrastructure; | |
| using Microsoft.Extensions.DependencyInjection; | |
| namespace MyApi.Extension | |
| { | |
| public static class ServiceColltectionExtensions | |
| { | |
| public static void AddCustomizedValidationError(this IMvcBuilder mvc) | |
| { | |
| mvc.ConfigureApiBehaviorOptions(setup => | |
| { | |
| setup.InvalidModelStateResponseFactory = (context) => | |
| { | |
| var problemDetailsErrorFactory = context.HttpContext.RequestServices.GetRequiredService<ProblemDetailsFactory>(); | |
| var instance = problemDetailsErrorFactory.CreateValidationProblemDetails(context.HttpContext, context.ModelState); | |
| instance.Detail = "See errors field for details."; | |
| instance.Instance = context.HttpContext.Request.Path; | |
| var actionExecutingContext = context as ActionExecutingContext; | |
| if (context.ModelState.ErrorCount > 0 && | |
| (actionExecutingContext?.ActionArguments.Count == context.ActionDescriptor.Parameters.Count)) | |
| { | |
| instance.Type = null; | |
| instance.Status = StatusCodes.Status422UnprocessableEntity; | |
| instance.Title = "One or more validation problem occurred."; | |
| return new UnprocessableEntityObjectResult(instance) | |
| { | |
| ContentTypes = { "application/problem+json" }, | |
| }; | |
| } | |
| instance.Status = StatusCodes.Status400BadRequest; | |
| instance.Title = "One or more validation problem occurred."; | |
| return new BadRequestObjectResult(instance) | |
| { | |
| ContentTypes = { "application/problem+json" }, | |
| }; | |
| }; | |
| }); | |
| } | |
| } | |
| } | |
| /* * | |
| * HOW TO USE: | |
| * public void ConfigureServices(IServiceCollection services) | |
| * { | |
| * services.AddControllers(options => { | |
| * options.ReturnHttpNotAcceptable = true; | |
| * }) | |
| * .AddXmlDataContractSerializerFormatters() /* Or JSON Formatter for content-type format */ | |
| * .AddCustomizedValidationError(); | |
| * } | |
| * | |
| * */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment