当响应为200时,它会正确返回结果。但是,当它是一个错误的请求时,它不能将结果作为反序列化的json返回,因为responseString实际上有一个JSON数组。所以当考虑到一个糟糕的请求时,我考虑跳过脱盐步骤。但是,现在我得到了结果,但是使用了转义引号,即{\“property \”:\“value \”},我可以想出一种方法,将错误的请求作为JSON返回但没有转义的char。
这是我的代码:
public async Task<TResponse> PostAsync<TRequest, TResponse>(Uri uri, TRequest request)
{
var jsonContent = (request as object).SerializeAsCamelCaseJson();
var requestString = await jsonContent.ReadAsStringAsync().ConfigureAwait(false);
Logger.Debug(requestString);
var result = await this.httpClient.PostAsync(uri, jsonContent).TimeoutAfter(this.Timeout).ConfigureAwait(false);
TResponse response;
string responseString;
if (result.IsSuccessStatusCode)
{
responseString = await result.Content.ReadAsStringAsync().TimeoutAfter(this.Timeout).ConfigureAwait(false);
response = JsonConvert.DeserializeObject<TResponse>(responseString);
return response;
}
responseString = await result.Content.ReadAsStringAsync().TimeoutAfter(this.Timeout).ConfigureAwait(false);
throw new Exception(responseString);
}