简体   繁体   English

以JSON格式返回Web API响应

[英]Returning the Web API response in JSON format

I am trying sending a response from the API as a JSON. 我正在尝试从API作为JSON发送响应。 Currently we are calling other web service multiple times consuming it and send all the responses together as a JSON. 当前,我们正在多次调用其他Web服务,以使用它,并将所有响应作为JSON一起发送。 The called web service returns response as a JSON. 调用的Web服务以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. 我不确定如何以JSON而不是XML的形式发送。

Something we did where I work was to create a custom class that extends ExceptionFilterAttribute . 我们所做的工作是创建一个扩展ExceptionFilterAttribute的自定义类。 Call it something like WebApiExceptionFilterAttribute . WebApiExceptionFilterAttribute这样称呼它。 Create an override for OnException and set the context.Response appropriately based on the exception. 创建一个覆盖OnException ,并设置context.Response适当基于异常的。 You can also set the HttpStatusCode if the exception indicates a specific result, such as NotFound, Forbidden, or BadRequest, instead of just InternalServerError. 您还可以设置HttpStatusCode如果异常指示特定结果,如NOTFOUND,故宫,或错误请求,而不是只InternalServerError。

Then, in Global.asax , in Application_Start() , add GlobalConfiguration.Configuration.Filters.Add(new WebApiExceptionFilterAttribute()); 然后,在Global.asaxApplication_Start() ,添加GlobalConfiguration.Configuration.Filters.Add(new WebApiExceptionFilterAttribute());

Finally, when defining an ApiController , add a [WebApiExceptionFilterAttribute] annotation to the class definition. 最后,在定义ApiController ,在类定义中添加[WebApiExceptionFilterAttribute]批注。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM