2017-07-20 32 views
-1

我找回賬號:如何反序列化或模仿的響應類型

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獲取響應類型?

+1

看看'task'的其他屬性(這不是'Task',應該重命名)。這與'JObject'無關。 – SLaks

+0

@slaks所以如果我想要返回響應類型和有效負載(JObject),那麼完成此操作的最有效的方法是什麼? –

+0

返回'HttpRequestMessage'或設置'Response'的屬性。 – SLaks

回答

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

我也可能不應該做雙重序列化和反序列化 –

+0

@l - '''''' - - ''''''''''''沒有序列化或在這個答案反序列化。原始字符串響應正在傳遞。 – Nkosi