即使数据有效,WebAPI验证错误也是如此

时间:2013-12-31 00:16:30

标签: c# jquery asp.net json asp.net-web-api

我创建了一个web api,之前它已成功运行。然而,某些事情发生了变化(不确定是什么),现在已经不再适用了。

我使用fiddler使用以下JSON数据将PUT编写为/ api / Dealer / 19:

  

{“notes”:[],“dealerId”:19,“name”:“4th Street Auto Co。”,“phone”:“888-776-5085”,“website”:“{{3} }“,”streetAddress“:”5109 Preston Highway“,”city“:”Louisville“,”state“:”KY“,”zipCode“:40213}

我收到400错误回复:

  

HTTP / 1.1 400错误请求   服务器:ASP.NET Development Server / 11.0.0.0   日期:2013年12月31日星期二00:07:12 GMT   X-AspNet-Version:4.0.30319   缓存控制:无缓存   Pragma:没有缓存   到期:-1   Content-Type:application / json;字符集= utf-8的   内容长度:123   连接:关闭

     

{“Dealer.Name”:“请输入姓名”,“Dealer.Phone”:“请输入电话号码”,“经销商。网站”:“请输入网站”}

我有一个ValidationActionFilter,它正在构建错误消息:

public class ValidationActionFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext context)
    {
        var modelState = context.ModelState;
        if (!modelState.IsValid)
        {
            var errors = new JObject();
            foreach (var key in modelState.Keys)
            {
                var state = modelState[key];
                if (state.Errors.Any())
                {
                    errors[key] = state.Errors.First().ErrorMessage;
                }
            }

            context.Response = context.Request.
                CreateResponse<JObject>(HttpStatusCode.BadRequest, errors);
        }
    }
}

我的模型看起来像这样:

public class Dealer
{
    public int DealerId { get; set; }

    [Required(ErrorMessage = "Please Enter Name")]
    [StringLength(100, ErrorMessage = "Name is too long")]
    public string Name { get; set; }

    [Required(ErrorMessage="Please Enter Phone Number")]
    [StringLength(14, ErrorMessage = "Phone is too long")]
    public string Phone { get; set; }

    [Required(ErrorMessage = "Please Enter Website")]
    [StringLength(250, ErrorMessage = "Website is too long")]
    public string Website { get; set; }

    [StringLength(100, ErrorMessage = "Street Address is too long")]
    public string StreetAddress { get; set; }

    [StringLength(50, ErrorMessage = "City is too long")]
    public string City { get; set; }

    [StringLength(50, ErrorMessage = "State is too long")]
    public string State { get; set; }

    public int ZipCode { get; set; }

    public virtual ICollection<Note> Notes { get; set; }
}

即使字段存在,导致验证错误的原因是什么?

谢谢!

2 个答案:

答案 0 :(得分:1)

我想MVC无法将数据绑定到您的模型,因此该模型为空?

如果是这种情况,请尝试重新格式化您发布的数据以反映模型

{"Dealer.Name":"..","Dealer.Phone":"..."...

而不是{"name":...,"phone":...}

答案 1 :(得分:0)

您的要求是 {“notes”:[],“dealerId”:19,“name”:“4th Street Auto Co。”,“phone”:“888-776-5085”,“website”:“http://www.cars.com/dealers/98681/4th-street-auto-co/”, “streetAddress”:“5109 Preston Highway”,“city”:“Louisville”,“state”:“KY”,“zipCode”:40213}

我认为mvc无法理解你的要求 我总是使用&gt;&gt; { “密钥”: “值”, “关键”: “值”}