HttpClient - PostAsJsonAsync

时间:2015-11-12 19:56:30

标签: c# asp.net asp.net-mvc

使用PostAsJsonAsync<T>(..)扩展程序时,我遇到了一个简单但烦人的问题,而我无法在任何地方找到解决以下问题的信息。

我的问题是生成的Json使用PascaCasing,我需要camelCasing按照实际标准。

这是一个可以重现问题的简单示例(来源:http://www.codeproject.com/Articles/611176/Calling-ASP-NET-WebAPI-using-HttpClient):

        HttpClient client = new HttpClient();
        client.BaseAddress = new Uri("http://localhost:56851/");

         client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));

        var user = new Users();

        user.FirstName = txtFirst.Text;
        user.Company = txtCompany.Text;
        user.LastName = txtLas.Text;
        user.Email = txtEmail.Text;
        user.PhoneNo = txtPhone.Text;
        user.Email = txtEmail.Text;

        var response = client.PostAsJsonAsync("api/User", user).Result;

        if (response.IsSuccessStatusCode)
        {
            MessageBox.Show("User Added");
            txtFirst.Text = "";
            txtLas.Text = "";
            txtPhone.Text = "";
            txtEmail.Text = "";
            txtCompany.Text = "";
            GetData();
        }
        else
        {
            MessageBox.Show("Error Code" + 
            response.StatusCode + " : Message - " + response.ReasonPhrase);
        }

1 个答案:

答案 0 :(得分:1)

尝试发送匿名类型。

var user = new {
    firstName = txtFirst.Text,
    company = txtCompany.Text,
    lastName = txtLas.Text,
    email = txtEmail.Text,
    phoneNo = txtPhone.Text,
    email = txtEmail.Text
};
var response = client.PostAsJsonAsync("api/User", user).Result;