MVC Web Api CamelCase属性名称不适用于BadRequest

时间:2014-05-09 18:29:21

标签: asp.net-web-api asp.net-web-api2

我在WebApiConfig.cs文件中有以下内容,它适用于良好的请求

var jsonFormatter = config.Formatters.JsonFormatter;
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

我的控制器中的顶行是

public async Task<IHttpActionResult> ForgotPassword(ForgotPasswordBindingModel model)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }
}

以下是我的模型被传递到控制器

public class ForgotPasswordBindingModel
{
    [Required]
    [Display(Name = "User name")]
    public string UserName { get; set; }

    [EmailAddress]
    [Display(Name = "Email")]
    public string Email { get; set; }
}

当我的模型被序列化回客户端时,UserName和Email未正确发布

Object {message: "The request is invalid.", modelState: Object}
message: "The request is invalid."
modelState: Object
model.Email: Array[1]
0: "The Email field is not a valid e-mail address."

对象本身ModelState似乎是正确的,并且当请求成功时,生成的对象正确完成,但badrequest的modelState属性似乎没有正确。 modelState.model.email应该有我的理解一个较低的套装&#39; E&#39;用于电子邮件我认为Config设置可以解决这个问题,但事实并非如此。任何人都有任何想法,为什么当模型状态被序列化后没有被正确地传播?

1 个答案:

答案 0 :(得分:0)

这可能是因为ModelState是一个字典,而CamelCaseContractResolver只处理模型的属性。

https://github.com/JamesNK/Newtonsoft.Json/blob/master/Src/Newtonsoft.Json/Serialization/CamelCasePropertyNamesContractResolver.cs