none
HttpClientExtensions.PostAsJsonAsync() change Json serializer settings RRS feed

  • Question

  • Hello All,

    I am trying to use the below class to post some data to remote server. The server accepts json in camel case(after serialization) only. 

    HttpClientExtensions.PostAsJsonAsync()

    Right now I made my properties inside class to camel case, but this is against the coding standard and do not want to continue with that. Mine is an asp.net mvc5 application. I tried to put the below code in Application_Start

    protected void Application_Start()
            {
                AreaRegistration.RegisterAllAreas();
                FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
                RouteConfig.RegisterRoutes(RouteTable.Routes);
                JsonConvert.DefaultSettings = () => new JsonSerializerSettings
                {
                    Formatting = Formatting.Indented,
                    ContractResolver = new CamelCasePropertyNamesContractResolver()
                };
            }

    But this is not working and I am getting a bad request from server(Http 400). Is it possible to change the json serializer settings of PostAsJsonAsync(). First of all does it use Newtonsoft.Json or its own native serializer? Any kind of  help will be appreciated.

    Wednesday, January 6, 2016 1:54 PM

Answers

  • Hi Sajan,

    By review the source code of HttpClientExtensions class. I find in PostAsJsonAsync method, it will use default JsonMediaTypeFormatter. Code below is for your reference.

    public static Task<HttpResponseMessage> PostAsJsonAsync<T>(this HttpClient client, Uri requestUri, T value, CancellationToken cancellationToken) 
    { 
        return client.PostAsync(requestUri, value, new JsonMediaTypeFormatter(), cancellationToken); 
    } 
    

    So, I suggest  you use PostAsync method instead of PostAsJsonAsync method to use a customize serializer.

    var formatter = new JsonMediaTypeFormatter();
    formatter.SerializerSettings = new JsonSerializerSettings
    {
        Formatting = Formatting.Indented,
        ContractResolver = new CamelCasePropertyNamesContractResolver()
    };
    HttpClient client = new HttpClient();
    client.PostAsync<yourtype>("yoururl", yourobject, formatter);
    Best Regards,
    Li Wang

    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Thursday, January 7, 2016 8:10 AM
    Moderator

All replies

  • Hi Sajan Emmanuel,

    >>First of all does it use Newtonsoft.Json or its own native serializer?

    JSON formatting is provided by the JsonMediaTypeFormatter class. By default, JsonMediaTypeFormatter uses the Json.NET library to perform serialization. So you need to change the setting like this.

    var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
    json.SerializerSettings =  new JsonSerializerSettings
    {
        Formatting = Formatting.Indented,
        ContractResolver = new CamelCasePropertyNamesContractResolver()
    };

    If you prefer, you can configure the JsonMediaTypeFormatter class to use the                 DataContractJsonSerializer instead of Json.NET. To do so, set the UseDataContractJsonSerializer property to true. And use DataContract and DataMember to make your type serializable.

    var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
    json.UseDataContractJsonSerializer = true;
    [DataContract(Name = "Student")]
    public class Student
    {
        [DataMember(Name = "StudentName")]
        public string Name { get; set; }
        [DataMember(Name = "StudentAge")]
        public int Age { get; set; }
    }
    Best Regards,
    Li Wang


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Thursday, January 7, 2016 2:27 AM
    Moderator
  • Hello,

    I added this inside my Global.asax file like below

     protected void Application_Start()
            {
                AreaRegistration.RegisterAllAreas();
                FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
                RouteConfig.RegisterRoutes(RouteTable.Routes);
                var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
                json.SerializerSettings = new JsonSerializerSettings
                {
                    Formatting = Formatting.Indented,
                    ContractResolver = new CamelCasePropertyNamesContractResolver()
                };
            }

    It's not working for me. Please note that mine is an MVC5 application and does not use web api. In order to get the references resolved, I added below Nuget packagaes too

      <package id="Microsoft.AspNet.WebApi.Client" version="5.2.3" targetFramework="net46" />
      <package id="Microsoft.AspNet.WebApi.Core" version="5.2.3" targetFramework="net46" />
      <package id="Microsoft.AspNet.WebApi.WebHost" version="5.2.3" targetFramework="net46" />

    Any idea why it is not working for me?

    Thursday, January 7, 2016 7:46 AM
  • Hi Sajan,

    By review the source code of HttpClientExtensions class. I find in PostAsJsonAsync method, it will use default JsonMediaTypeFormatter. Code below is for your reference.

    public static Task<HttpResponseMessage> PostAsJsonAsync<T>(this HttpClient client, Uri requestUri, T value, CancellationToken cancellationToken) 
    { 
        return client.PostAsync(requestUri, value, new JsonMediaTypeFormatter(), cancellationToken); 
    } 
    

    So, I suggest  you use PostAsync method instead of PostAsJsonAsync method to use a customize serializer.

    var formatter = new JsonMediaTypeFormatter();
    formatter.SerializerSettings = new JsonSerializerSettings
    {
        Formatting = Formatting.Indented,
        ContractResolver = new CamelCasePropertyNamesContractResolver()
    };
    HttpClient client = new HttpClient();
    client.PostAsync<yourtype>("yoururl", yourobject, formatter);
    Best Regards,
    Li Wang

    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Thursday, January 7, 2016 8:10 AM
    Moderator