HttpClient - PostAsJsonAsync

本文关键字:PostAsJsonAsync HttpClient | 更新日期: 2023-09-27 18:21:46

在使用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);
        }

HttpClient - PostAsJsonAsync

尝试只发送一个匿名类型。

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