ASP.NET MVC模型绑定不解析

时间:2013-08-14 10:37:29

标签: json asp.net-mvc-4

我在使用ASP.NET MVC应用程序解析模型时遇到一些问题,我只是得到“null”。

这是我的ASP.NET MVC操作

public AdobeReturnSet<UserModel> Post([FromBody]UserModel model)

我也试过没有[FromBody],但没有帮助。

这是我的模特

public class UserModel
    {
        public int AdobeId { get; set; }

        [Required]
        [StringLength(500)]
        public string FristName { get; set; }
        [Required]
        [StringLength(500)]
        public string LastName { get; set; }
        [Required]
        [StringLength(250)]
        [EmailAddress]
        public string Email { get; set; }
        [Required]
        public string OrganizationIdentification { get; set; }

        public string Organization { get; set; }
        public string OrganizationFull { get; set; }
}

这就是我发送请求的方式

using (WebClient wc = new WebClient())
            {
                wc.Headers[HttpRequestHeader.Accept] = "application/json";
                wc.Headers[HttpRequestHeader.AcceptCharset] = "utf-8";
                wc.Headers[HttpRequestHeader.ContentType] = "application/json";
                result = wc.UploadString(url, "POST", data);
            }

当达到正确的操作时,网址是正确的,这是数据的值:

{"AdobeId":0,"FristName":"Kasper Rune","LastName":"Søgaard","Email":"krus@arcanic.dk","OrganizationIdentification":null,"Organization":null,"OrganizationFull":null}

但是当请求到达我的动作时,模型就是null。 它是一个ApiController,如果它改变任何东西。

1 个答案:

答案 0 :(得分:2)

看起来像编码问题。请尝试使用UploadData方法,并使用UTF-8编码:

using (var wc = new WebClient())
{
    var data = Encoding.UTF8.GetBytes(@"{""AdobeId"":0,""FristName"":""Kasper Rune"",""LastName"":""Søgaard"",""Email"":""krus@arcanic.dk"",""OrganizationIdentification"":null,""Organization"":null,""OrganizationFull"":null}");

    wc.Headers[HttpRequestHeader.Accept] = "application/json";
    wc.Headers[HttpRequestHeader.ContentType] = "application/json";
    byte[] result = wc.UploadData(url, "POST", data);
    string json = Encoding.UTF8.GetString(result);
}

或者你可以使用新的HttpClient:

using (var client = new HttpClient())
{
    client.DefaultRequestHeaders.ConnectionClose = true;
    var value = new
    {
        AdobeId = 0,
        FristName = "Kasper Rune",
        LastName = "Søgaard",
        Email = "krus@arcanic.dk",
    };
    var result = client.PostAsJsonAsync(url, value).Result;
    if (result.IsSuccessStatusCode)
    {
        string json = result.Content.ReadAsStringAsync().Result;
    }
}

此外,您可能会在FristName处输入错字,该错字可能应为FirstName