我正在尝试从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我上面的代码抛出错误。
除了没有序列化为json,似乎你在你的模型中有循环引用:https://stackoverflow.com/questions/23098191/failed-to-serialize-the-response-in-web-api-with- json。在web api中,根据你的客户端有一个内容协商过程来返回预期的格式,你不应该在这里硬编码你的json格式。 –
你确定你不是试图反序列化一个错误?什么是返回的http状态码? –
@PeterBons http状态码是200.但抛出上述错误 – xyz