Handling Model Validation in ASP.NET Web API
When working with data in your ASP.NET Web API applications, model validation plays a crucial role in ensuring data integrity. The ModelState property provides a convenient mechanism for validating request data against your model's rules.
Consider the following scenario:
You have a model:
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; } }
In your API controller, you have a Post action:
public void Post(Enquiry enquiry) { enquiry.EnquiryDate = DateTime.Now; context.DaybookEnquiries.Add(enquiry); context.SaveChanges(); }
To implement model validation, you can use the ModelState.IsValid property:
public void Post(Enquiry enquiry) { if (ModelState.IsValid) { enquiry.EnquiryDate = DateTime.Now; context.DaybookEnquiries.Add(enquiry); context.SaveChanges(); } }
If the model is valid, the action proceeds to create the entity in the database. Otherwise, it returns a 400 (Bad Request) response with the validation error messages.
For cleaner separation of concerns, you can also use an action filter for model validation:
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); } } }
Apply this filter to your Post action:
[ValidationActionFilter] public void Post(Enquiry enquiry) { enquiry.EnquiryDate = DateTime.Now; context.DaybookEnquiries.Add(enquiry); context.SaveChanges(); }
By implementing model validation using either of these approaches, you can ensure that your API endpoint only accepts valid data and provides meaningful error messages to users.
The above is the detailed content of How Can I Effectively Handle Model Validation in ASP.NET Web API?. For more information, please follow other related articles on the PHP Chinese website!