Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle ModelState Validation in ASP.NET Web API

I was wondering how I can achieve model validation with ASP.NET Web API. I have my model like so:

public class Enquiry {     [Key]     public int EnquiryId { get; set; }     [Required]     public DateTime EnquiryDate { get; set; }     [Required]     public string CustomerAccountNumber { get; set; }     [Required]     public string ContactName { get; set; } } 

I then have a Post action in my API Controller:

public void Post(Enquiry enquiry) {     enquiry.EnquiryDate = DateTime.Now;     context.DaybookEnquiries.Add(enquiry);     context.SaveChanges(); } 

How do I add if(ModelState.IsValid) and then handle the error message to pass down to the user?

like image 285
CallumVass Avatar asked Jul 27 '12 11:07

CallumVass


People also ask

How can validation errors be handled in Web API?

Handling Validation Errors Web API does not automatically return an error to the client when validation fails. It is up to the controller action to check the model state and respond appropriately. If model validation fails, this filter returns an HTTP response that contains the validation errors.

Is validation handled differently in Web API than in MVC?

We can perform model validation in MVC in an easy way. In API, when sending the request by the client or user to web API, then before doing the next process, it checks the empty validation and handles the validation error using data annotation in WEB API.

How do I know if my ModelState is valid?

Below the Form, the ModelState. IsValid property is checked and if the Model is valid, then the value if the ViewBag object is displayed using Razor syntax in ASP.Net MVC.


2 Answers

For separation of concern, I would suggest you use action filter for model validation, so you don't need to care much how to do validation in your api controller:

using System.Net; using System.Net.Http; using System.Web.Http.Controllers; using System.Web.Http.Filters;  namespace System.Web.Http.Filters {     public class ValidationActionFilter : ActionFilterAttribute     {         public override void OnActionExecuting(HttpActionContext actionContext)         {             var modelState = actionContext.ModelState;              if (!modelState.IsValid)                 actionContext.Response = actionContext.Request                      .CreateErrorResponse(HttpStatusCode.BadRequest, modelState);         }     } } 
like image 65
cuongle Avatar answered Sep 29 '22 08:09

cuongle


Maybe not what you were looking for, but perhaps nice for someone to know:

If you are using .net Web Api 2 you could just do the following:

if (!ModelState.IsValid)      return BadRequest(); 

Depending on the model errors, you get this result:

{    Message: "The request is invalid."    ModelState: {        model.PropertyA: [             "The PropertyA field is required."        ],        model.PropertyB: [              "The PropertyB field is required."        ]    } } 
like image 36
Are Almaas Avatar answered Sep 29 '22 07:09

Are Almaas