Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save Redouane64/e0f21c0cc7b2efe42af653e8491e140d to your computer and use it in GitHub Desktop.

Select an option

Save Redouane64/e0f21c0cc7b2efe42af653e8491e140d to your computer and use it in GitHub Desktop.
AspNet Web API Invalid Model State Response Configuration
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