【问题标题】:Returning the Web API response in JSON format以 JSON 格式返回 Web API 响应
【发布时间】:2017-10-20 13:53:39
【问题描述】:

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

    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 之外,您的模型中似乎还有循环引用:stackoverflow.com/questions/23098191/…。在 web api 中,有一个内容协商过程来根据您的客户端返回预期的格式,您不应该在这里硬编码您的 json 格式。
  • 您确定您没有尝试反序列化错误吗?返回的http状态码是什么?
  • @PeterBons http状态码是200。但是抛出上面的错误
  • @KhanhTO 但是,如果我想在浏览器中查看响应,我该怎么做。还有循环引用我不确定我是新来的什么问题
  • responsefile的内容是什么?你检查了吗?

标签: c# json asp.net-web-api serialization json-deserialization


【解决方案1】:

我们在我工作的地方所做的事情是创建一个扩展 ExceptionFilterAttribute 的自定义类。称之为WebApiExceptionFilterAttribute。为OnException 创建一个覆盖并根据异常适当地设置context.Response。如果异常指示特定结果,例如 NotFound、Forbidden 或 BadRequest,您也可以设置 HttpStatusCode,而不仅仅是 InternalServerError。

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

最后,在定义ApiController时,在类定义中添加[WebApiExceptionFilterAttribute]注解。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-11
    • 2014-09-11
    • 2019-03-15
    • 1970-01-01
    • 1970-01-01
    • 2019-05-18
    • 2022-01-15
    • 1970-01-01
    相关资源
    最近更新 更多