0

I am trying sending a response from the API as a JSON. Currently we are calling other web service multiple times consuming it and send all the responses together as a JSON. The called web service returns response as a JSON. And below is what I am doing

    List<Models.DTO.RootObject> i_response = new List<Models.TO.RootObject>();
    public async Task<IHttpActionResult> Get()
    {
    .....
   foreach (int req_id in reqIdLst)
   { 
     using (var client_request = new HttpClient())
      {
       string request_Uri = BaseURL_iLab;
       Uri uri_request = new Uri(request_Uri);
       client_request.BaseAddress = uri_request;
       client_request.DefaultRequestHeaders.Accept.Clear();
       client_request.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
       client_request.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);

       var request_response = await client_request.GetAsync(uri_request);
       var responsefile = await request_response.Content.ReadAsStringAsync();

        var request_returnDataObj = JsonConvert.DeserializeObject<Models.DTO.RootObject>(responsefile);

         i_response.Add(request_returnDataObj);
     }}
      return Ok(i_response);
  }}

But my above code throws error when debugging as

<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>
The 'ObjectContent`1' type failed to serialize the response body for content 
type 'application/xml; charset=utf-8'.
</ExceptionMessage>
<ExceptionType>System.InvalidOperationException</ExceptionType>
<StackTrace/>
<InnerException>

I am not sure how to send as a JSON instead of a XML.

xyz
  • 531
  • 1
  • 10
  • 31
  • 1
    Besides not serializing to json, it seems like you have circular references in your model: https://stackoverflow.com/questions/23098191/failed-to-serialize-the-response-in-web-api-with-json . In web api, there is a content negotiation process to return the expected format depending on your client, you should not hard code your json format here. – Khanh TO Oct 20 '17 at 14:03
  • You sure you are not attempting to deserializing an error? what is the returned http status code? – Peter Bons Oct 20 '17 at 14:05
  • @PeterBons the http status code is 200. But throwing the above error – xyz Oct 20 '17 at 14:10
  • @KhanhTO But if I want to see the response in the browser how do I do that. Also the circular reference I am not sure what is wrong I am new to this – xyz Oct 20 '17 at 14:13
  • What is the content of `responsefile`? did you inspect it? – Peter Bons Oct 20 '17 at 14:23
  • @PeterBons responsefile is getting the response back from the web service as JSON. – xyz Oct 20 '17 at 14:37
  • Are you sure that your JSON is really matching RootObject ? – User.Anonymous Oct 20 '17 at 14:46

1 Answers1

0

Something we did where I work was to create a custom class that extends ExceptionFilterAttribute. Call it something like WebApiExceptionFilterAttribute. Create an override for OnException and set the context.Response appropriately based on the exception. You can also set the HttpStatusCode if the exception indicates a specific result, such as NotFound, Forbidden, or BadRequest, instead of just InternalServerError.

Then, in Global.asax, in Application_Start(), add GlobalConfiguration.Configuration.Filters.Add(new WebApiExceptionFilterAttribute());

Finally, when defining an ApiController, add a [WebApiExceptionFilterAttribute] annotation to the class definition.

CodeMonkey
  • 419
  • 2
  • 10