locked
Regarding web api and send/receive to and from json to action RRS feed

  • Question

  • User264732274 posted

    I just add the following in App_Start/WebApiConfig.cs class in my MVC Web API project.

    config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html")

    i just like to verify one things that when we set that response will be always in json always. so when we send json from client to action over get or post method then do i need to again specify that i am sending json to action like below way ?

    HttpClient client = new HttpClient();
    client.BaseAddress = new Uri("http://localhost:38762/api/customer/AddCustome");
    client.DefaultRequestHeaders
      .Accept
      .Add(new MediaTypeWithQualityHeaderValue("application/json"));

    please guide me that we need to said to web api for request and response both case that i am sending json or i want json as response ?

    Monday, August 29, 2016 6:51 PM

Answers

  • User36583972 posted

    Hi sudip_inn,

    do i need to again specify that i am sending json to action like below way ?

    Yes, you need to specify that you are sending JSON data to action.

    that i am sending json

    Use a StringContent, with the JSON representation of your JSON object

      var responseS = httpClient.PostAsync(uri, new StringContent(JsonConvert.SerializeObject(OBJECT), Encoding.UTF8, "application/json"));
    

    or i want json as response ?

    You can use the following code to return a JSON data.

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

    Best Regards,

    Yohann Lu

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, August 30, 2016 2:27 AM