2017-10-20 153 views
0

我正在尝试从API发送响应作为JSON。目前,我们正在多次调用其他Web服务,并将所有响应作为JSON发送。被调用的Web服务将响应作为JSON返回。以下是我在做什么以JSON格式返回Web API响应

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); 
    }} 

但作为

<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> 

调试时,我不知道如何发送的JSON而不是XML我上面的代码抛出错误。

+1

除了没有序列化为json,似乎你在你的模型中有循环引用:https://stackoverflow.com/questions/23098191/failed-to-serialize-the-response-in-web-api-with- json。在web api中,根据你的客户端有一个内容协商过程来返回预期的格式,你不应该在这里硬编码你的json格式。 –

+0

你确定你不是试图反序列化一个错误?什么是返回的http状态码? –

+0

@PeterBons http状态码是200.但抛出上述错误 – xyz

回答

0

我们在我工作的地方做了一件事,就是创建一个自定义的类来扩展ExceptionFilterAttribute。称之为WebApiExceptionFilterAttribute。创建OnException的替代,并根据例外情况适当地设置context.Response。如果异常指示特定结果(例如NotFound,Forbidden或BadRequest)而不是仅仅是InternalServerError,则还可以设置HttpStatusCode

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

最后,限定ApiController时,添加一个[WebApiExceptionFilterAttribute]注释到类定义。