Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save wellingtonjhn/767a151c36bd021bc0451c4ac851d528 to your computer and use it in GitHub Desktop.

Select an option

Save wellingtonjhn/767a151c36bd021bc0451c4ac851d528 to your computer and use it in GitHub Desktop.
Problem Details Model State Behavior
public static class ProblemDetailsExtensions
{
public static IServiceCollection ConfigureProblemDetailsModelState(this IServiceCollection services)
{
return services.Configure<ApiBehaviorOptions>(options =>
{
options.InvalidModelStateResponseFactory = context =>
{
var problemDetails = new ValidationProblemDetails(context.ModelState)
{
Instance = context.HttpContext.Request.Path,
Status = StatusCodes.Status400BadRequest,
Detail = "Please refer to the errors property for additional details"
};
return new BadRequestObjectResult(problemDetails)
{
ContentTypes = { "application/problem+json", "application/problem+xml" }
};
};
});
}
}
public class Item
{
[Required]
public string Name { get; }
[Range(1, 10)]
public int Value { get; }
public Item(string name, int value)
{
Name = name;
Value = value;
}
}
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
[HttpPost]
public ActionResult Post(Item item)
{
return Ok();
}
}
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.ConfigureProblemDetailsModelState();
}
//... código omitido
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment