一尘不染

在ASP.NET Web API中处理ModelState验证

c#

我想知道如何使用ASP.NET Web API进行模型验证。我有这样的模型:

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; }
}

然后,我在API控制器中执行了Post操作:

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

如何添加if(ModelState.IsValid)然后处理错误消息以传递给用户?


阅读 360

收藏
2020-05-19

共1个答案

一尘不染

为了分开关注,我建议您使用动作过滤器进行模型验证,因此您无需过多关心如何在api控制器中进行验证:

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);
        }
    }
}
2020-05-19