Home >Backend Development >C++ >How to Handle Model State Validation in ASP.NET Web API?
Validating models in ASP.NET Web API is a common task. Model validation can be achieved by using the data annotation properties and the ModelState property.
The model given in the example defines several properties, each with a Required data annotation attribute indicating that the field is required.
In the example, in the Post action method, no explicit validation is performed on the model. To implement model validation, you can add the following code to the beginning of the method:
if (!ModelState.IsValid) { // Handle validation errors }
In case the ModelState is invalid, it indicates that the model validation failed. At this point, you can take the following steps to handle the error message:
You can also use Action Filter for model verification. An Action Filter is a custom attribute that can run before or after an API operation is executed. The following example shows how to use an Action Filter for model validation:
public class ValidationActionFilter : ActionFilterAttribute { public override void OnActionExecuting(HttpActionContext actionContext) { if (!actionContext.ModelState.IsValid) { actionContext.Response = actionContext.Request .CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState); } } }
Applying this Action Filter to an API operation automatically validates the model and returns an appropriate error response if the model state is invalid.
The above is the detailed content of How to Handle Model State Validation in ASP.NET Web API?. For more information, please follow other related articles on the PHP Chinese website!