What is Model Validation?
Model validation adds checks for any model state errors and produces a BadRequestResult if the model state is invalid. Some common validations are present in system.data.componentModel.DataAnnotations. One can write custom validation attributes to address specific validation scenarios.
What is the need for Customizing the response
In specific scenarios, we might need to include more details in our response so that user can interpret it well and correct the request easily. There may be several other reasons behind customizing the response due to model validation.
How to achieve this in .Net Core 2.2
ConfigureApiBehaviorOptions is an extension method of IMvcbulder interface. ApiBehaviorOptions class has the property of Func delegate InvalidModelStateResponseFactory, which gives developers the control to write custom responses.
Let's have a look at ConfigureServices method present in startup class and then examine it line by line. All explanations are given inline as comments so that they can be quickly understood.
- public void ConfigureServices(IServiceCollection services) {
-
- services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
-
-
-
-
-
- .ConfigureApiBehaviorOptions(options => {
-
-
-
-
- options.InvalidModelStateResponseFactory = actionContext => {
-
-
-
-
- return CustomErrorResponse(actionContext);
- };
- });
- }
Here is a code snippet for the CustomErrorResponse method and the custom Error class:
-
- private BadRequestObjectResult CustomErrorResponse(ActionContext actionContext) {
-
-
- return new BadRequestObjectResult(actionContext.ModelState
- .Where(modelError => modelError.Value.Errors.Count > 0)
- .Select(modelError => new Error {
- ErrorField = modelError.Key,
- ErrorDescription = modelError.Value.Errors.FirstOrDefault().ErrorMessage
- }).ToList());
- }
-
- public class Error
- {
- public string ErrorField { get; set; }
- public string ErrorDescription { get; set; }
- }
Please be advised that this article is a quick reference and not a complete guide on configuring ApiBehaviourOptions. Any suggestions to help make the article more concise are welcome.