8

I have created a Controller and method which i use to get data from an API. I use HttpResponseMessage to get the response. Everything works fine but i can not get the exact data i want in JSON format.
Method looks like below:

public class TestController : ApiController
    {
        [HttpGet]

        public async Task<IHttpActionResult> TestMethod(...)
        {
            string _apiUrl = String.Format("...");
            string _baseAddress = "...";

            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(_baseAddress);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                HttpResponseMessage response = await client.GetAsync(_apiUrl);


                if (response.IsSuccessStatusCode)
                {
                    return Json(response);
                }
            }
            return NotFound();
        }
    }

The response i get looks like:

{
  "Version": {
    "Major": 1,
    "Minor": 1,
    "Build": -1,
    "Revision": -1,
    "MajorRevision": -1,
    "MinorRevision": -1
  },
  "Content": {
    "Headers": [
      {
        "Key": "Content-Length",
        "Value": [
          "359"
        ]
      },
      {
        "Key": "Content-Type",
        "Value": [
          "application/json; charset=utf-8"
        ]
      },
      {
        "Key": "Expires",
        "Value": [
          "-1"
        ]
      }
    ]
  },
  "StatusCode": 200,
  "ReasonPhrase": "OK",
  "Headers": [
    {
      "Key": "Pragma",
      "Value": [
        "no-cache"
      ]
    },
    {
      "Key": "X-SourceFiles",
      "Value": ["..."
      ]
    },
    {
      "Key": "Cache-Control",
      "Value": [
        "no-cache"
      ]
    },
    {
      "Key": "Date",
      "Value": [
        "Thu, 21 Jul 2016 13:25:54 GMT"
      ]
    },
    {
      "Key": "Server",
      "Value": [
        "Microsoft-IIS/10.0"
      ]
    },
    {
      "Key": "X-AspNet-Version",
      "Value": [
        "4.0.30319"
      ]
    },
    {
      "Key": "X-Powered-By",
      "Value": [
        "ASP.NET"
      ]
    }
  ],
  "RequestMessage": {
    "Version": {
      "Major": 1,
      "Minor": 1,
      "Build": -1,
      "Revision": -1,
      "MajorRevision": -1,
      "MinorRevision": -1
    },
    "Content": null,
    "Method": {
      "Method": "GET"
    },
    "RequestUri": "...",
    "Headers": [
      {
        "Key": "Accept",
        "Value": [
          "application/json"
        ]
      }
    ],
    "Properties": {}
  },
  "IsSuccessStatusCode": true
}

But normaly, the API return this value (xml format):

<License>
  <Existing>
    <Amount>0</Amount>
    <Quantity>0</Quantity>
    <UnitAmount>0</UnitAmount>
  </Existing>
<New>
   <Amount>400</Amount>
   <Quantity>50</Quantity>
   <UnitAmount>8</UnitAmount>
</New>
<Result>
   <Amount>400</Amount>
   <Quantity>50</Quantity>
   <UnitAmount>8</UnitAmount>
</Result>
</License>
   <PartnerDiscount i:nil="true"/>
</CalculatorResult>

How can i extract these values from the API request.If i execute the "RequestUri"from API response i get the exact data. What am i missing?

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
etrupja
  • 2,710
  • 6
  • 22
  • 37
  • 2
    You don't want to serialise the entire response, just the `response.Content`. That's null in this case, apparently, so something else must be wrong too... – Charles Mager Jul 21 '16 at 13:43
  • You might try http://stackoverflow.com/a/15936272/423105 – LarsH Jul 21 '16 at 13:46
  • When i use response.Content i get this value: {"Headers":[{"Key":"Content-Length","Value":["359"]},{"Key":"Content-Type","Value":["application/json; charset=utf-8"]},{"Key":"Expires","Value":["-1"]}]} – etrupja Jul 21 '16 at 13:46
  • You're returning the entire HTTP response from the API. What do you want to do with the XML response, exactly? Convert it to JSON and return that? – CodeCaster Jul 21 '16 at 13:55
  • @CodeCaster Yes, exactly. – etrupja Jul 21 '16 at 14:07

1 Answers1

7

You need to extract the body of the response and return that

public class TestController : ApiController
{
    [HttpGet]
    public async Task<IHttpActionResult> TestMethod(...)
    {
        string _apiUrl = String.Format("...");
        string _baseAddress = "...";

        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri(_baseAddress);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            var responseMessage = await client.GetAsync(_apiUrl);

            if (responseMessage.IsSuccessStatusCode)
            {
                var response = Request.CreateResponse(HttpStatusCode.OK);
                response.Content = responseMessage.Content;
                return ResponseMessage(response);
            }
        }
        return NotFound();
    }
}

Here is another option using ExpandoObject.

if (responseMessage.IsSuccessStatusCode)
{
    var data =  await responseMessage.Content.ReadAsAsync<ExpandoObject>(); 
    return Json(data);
}
Nkosi
  • 235,767
  • 35
  • 427
  • 472
  • The response is XML. You don't want to return a JSON-encoded XML string. – CodeCaster Jul 21 '16 at 13:54
  • @CodeCaster You don't know that for a fact. The request headers are asking for JSON. – toadflakz Jul 21 '16 at 13:57
  • Oh that's right, I didn't read the OP's serialized HTTP response, I only looked at the example XML. – CodeCaster Jul 21 '16 at 13:59
  • @CodeCaster I believe that the xml is just a representation of the data returned. The header says it is return json. – Nkosi Jul 21 '16 at 14:00
  • The data i get now is the right data but the format is not right: "{\"License\":{\"New\":{\"Quantity\":50.0,\"UnitAmount\":8.0,\"Amount\":400.0},\"Existing\":{\"Quantity\":0.0,\"UnitAmount\":0.0,\"Amount\":0.0},\"Result\":{\"Quantity\":50.0,\"UnitAmount\":8.0,\"Amount\":400.0}},\"ContractPerYear\":null,\"ContractMonth\":null,\"ContractDay\":null,\"Contract\":null,\"ExistingLicenseDiscount\":null,\"ContractDiscount\":null,\"PartnerDiscount\":null,\"Discount\":null}" – etrupja Jul 21 '16 at 14:04
  • Opps. updateing. Its formatting the Json string. my bad – Nkosi Jul 21 '16 at 14:06
  • @Nkosi No problem. Thanks for the time – etrupja Jul 21 '16 at 14:18
  • @Nkosi with changes you did i get valid JSON: {"License":null,"ContractPerYear":null,"ContractMonth":null,"ContractDay":null,"Contract":null,"ExistingLicenseDiscount":null,"ContractDiscount":null,"PartnerDiscount":null,"Discount":null} But not the right one. – etrupja Jul 21 '16 at 14:45
  • That is what is being returned from the other api. You should confirm that the api call returns what you want as the code above is basically acting as a proxy just passing the data on to the caller – Nkosi Jul 21 '16 at 14:48