Omar Kh

Omar Kh

  • NA
  • 301
  • 21.8k

How I can return json object in api controller?

Apr 18 2021 7:10 AM
im using WebApi to make a webservice
as follow:
  1. using RestSharp;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.IO;  
  5. using System.Linq;  
  6. using System.Net;  
  7. using System.Net.Http;  
  8. using System.Web.Http;  
  9. using Newtonsoft.Json;  
  10.   
  11. namespace test.Controllers  
  12. {  
  13.     public class ValuesController : ApiController  
  14.     {  
  15.         public class WebAgent  
  16.         {  
  17.             public string Agent_no { getset; }  
  18.             public string Agent_Name { getset; }  
  19.         }  
  20.   
  21.         public string GetAgent([FromBody] string a_body)  
  22.         {     
  23.             dynamic stuff = JsonConvert.DeserializeObject(a_body);  
  24.             string agent = stuff.agent_no.ToString();  
  25.             string name = stuff.agent_name.ToString();  
  26.             try  
  27.             {  
  28.                 var test = new WebAgent()  
  29.                 {  
  30.                     Agent_no = agent,  
  31.                     Agent_Name = name  
  32.                 };  
  33.                 JsonSerializerSettings settings = new JsonSerializerSettings  
  34.                 {  
  35.                     NullValueHandling = NullValueHandling.Ignore,  
  36.                     Formatting = Formatting.Indented  
  37.                 };  
  38.                 var result= JsonConvert.SerializeObject(test,settings);  
  39.                 return result;  
  40.   
  41.             }  
  42.             catch (WebException e)  
  43.             {  
  44.                 var message = e.Message;  
  45.                 using (var reader = new StreamReader(e.Response.GetResponseStream()))  
  46.                 {  
  47.                     var content = reader.ReadToEnd();  
  48.                     return content.ToString();  
  49.                 }  
  50.             }  
  51.             finally  
  52.             {  
  53.   
  54.             }  
  55.         }  
  56.     }  
  57. }  
and everything just working fine
but when i try to call my webapi service from postman i got the following response
  1. "{\r\n \"Agent_no\": \"122331\",\r\n \"Agent_Name\": \"sabatini\"\r\n}"  
instead of: 
  1. "{"Agent_no": "122331","Agent_Name": "sabatini"}"  
i have tried to add
  1. config.Formatters.JsonFormatter.S‌​erializerSettings = new JsonSerializerSettings  
  2.             {  
  3.                 NullValueHandling = NullValueHandling.Ignore,  
  4.                 Formatting = Formatting.Indented  
  5.             };  
 to the WebApiConfig.cs but still get the same response !
i need help !
thanks 

Answers (2)