提问者:小点点

在ASP.NET Web API中处理模型状态验证


我想知道如何用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();
}

如何添加,然后处理向下传递给用户的错误消息?


共3个答案

匿名用户

对于关注点的分离,我建议您使用action filter进行模型验证,这样您就不需要太关心如何在您的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);
        }
    }
}

匿名用户

也许不是你想要的,但也许让人知道是件好事:

如果您正在使用。NET Web API2,则只需执行以下操作:

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

根据模型错误,您会得到以下结果:

{
   Message: "The request is invalid."
   ModelState: {
       model.PropertyA: [
            "The PropertyA field is required."
       ],
       model.PropertyB: [
             "The PropertyB field is required."
       ]
   }
}

匿名用户

像这样,例如:

public HttpResponseMessage Post(Person person)
{
    if (ModelState.IsValid)
    {
        PersonDB.Add(person);
        return Request.CreateResponse(HttpStatusCode.Created, person);
    }
    else
    {
        // the code below should probably be refactored into a GetModelErrors
        // method on your BaseApiController or something like that

        var errors = new List<string>();
        foreach (var state in ModelState)
        {
            foreach (var error in state.Value.Errors)
            {
                errors.Add(error.ErrorMessage);
            }
        }
        return Request.CreateResponse(HttpStatusCode.Forbidden, errors);
    }
}

这将返回如下响应(假设JSON,但XML的基本原理相同):

HTTP/1.1 400 Bad Request
Content-Type: application/json; charset=utf-8
(some headers removed here)

["A value is required.","The field First is required.","Some custom errorm essage."]

当然,您可以以任何方式构造错误对象/列表,例如添加字段名,字段ID等。

即使它是一个“单向”Ajax调用,比如一个新实体的POST,您仍然应该返回一些东西给调用者-一些指示请求是否成功的东西。设想一个站点,您的用户将通过AJAX POST请求添加一些关于自己的信息。如果他们试图输入的信息无效怎么办?他们如何知道他们的保存操作是否成功?

最好的方法是使用好的旧HTTP状态代码,如等。这样,JavaScript就可以使用正确的回调(错误,成功等)正确地处理失败。

下面是一个使用ActionFilter和jQuery的更高级版本的教程:http://asp.net/web-api/videos/getting-started/custom-validation