Last active
January 13, 2019 22:24
-
-
Save wellingtonjhn/767a151c36bd021bc0451c4ac851d528 to your computer and use it in GitHub Desktop.
Problem Details Model State Behavior
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
| 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" } | |
| }; | |
| }; | |
| }); | |
| } | |
| } |
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
| 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; | |
| } | |
| } |
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
| [Route("api/[controller]")] | |
| [ApiController] | |
| public class ValuesController : ControllerBase | |
| { | |
| [HttpPost] | |
| public ActionResult Post(Item item) | |
| { | |
| return Ok(); | |
| } | |
| } |
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
| 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