HttpClient - PostAsJsonAsync

倾然丶 夕夏残阳落幕 提交于 2021-02-10 05:13:15

问题


I'm experiencing a simple yet annoying issue when using the PostAsJsonAsync<T>(..) extension method and I can't find information on fixing the following issue anywhere.

My issue is that the Json that gets generated uses PascaCasing and I require camelCasing as per the actual standard.

Here's a simple sample that can reproduce the issue (source: 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:


try just sending an anonymous type.

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;


来源:https://stackoverflow.com/questions/33680203/httpclient-postasjsonasync

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!