【问题标题】:How to deserialize or mimic the response type如何反序列化或模仿响应类型
【发布时间】:2017-12-26 13:22:17
【问题描述】:

我正在检索帐户:

    public async Task<JObject> GetAccount(string query)
    {
        var task = await Client.Instance.GetAsync(Client.Instance.BaseAddress + query);
        var jsonString = await task.Content.ReadAsStringAsync();
        var account = JsonConvert.DeserializeObject<JObject>(jsonString);
        return account;
    }

无论Client.Instance.GetAsync... 返回 200 还是 400 或任何其他响应类型,当响应反序列化到帐户 (JObject) 时,响应始终为 200。

我们如何从 JObject 中获取响应类型?

【问题讨论】:

  • 查看task的其他属性(不是Task,应该重命名)。这与JObject无关。
  • @slaks 所以如果我想返回响应类型和有效负载(JObject),那么最实用的方法是什么?
  • 返回HttpRequestMessage 或设置Response 的属性。

标签: c# asp.net .net asp.net-web-api odata


【解决方案1】:

您从内部查询的响应中获取响应类型。该操作基本上充当代理。使用来自内部查询的响应来构造传递给调用客户端的响应。

public async Task<IHttpActionResult> GetAccount(string query) {
    //get the query response NOTE: assuming it is HttpResponseMessage
    var queryResponse = await Client.Instance.GetAsync(Client.Instance.BaseAddress + query);
    //get the status code for pass through
    var queryResponseStatus = queryResponse.StatusCode;
    //content to be passed on in the response
    var jsonString = await queryResponse.Content.ReadAsStringAsync();
    //create response message with status code
    var responseMessage = Request.CreateResponse(queryResponseStatus);
    //assign the content of the response
    responseMessage.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");
    //return the result
    return ResponseMessage(responseMessage);
}

【讨论】:

  • 我也不应该做双重序列化和反序列化
  • @l--''''''---------'''''''''''' 这个答案中没有序列化或反序列化。原始字符串响应正在传递。
猜你喜欢
  • 2023-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-19
  • 2022-01-17
  • 1970-01-01
  • 2018-07-17
相关资源
最近更新 更多