asp.net HttpClient在发送同步请求时抛出400个错误的异常

时间:2015-01-20 20:39:33

标签: c# asp.net .net httpclient

以下代码在我收到400错误时抛出异常。因此,我永远无法获得返回响应,因为异常总是被捕获。

using (var client = new HttpClient())
{
    try
    {
        var data = "...";

        var RequestBody = JsonConvert.SerializeObject(data);

        var requestUri = new Uri("url to error");
        var content = new StringContent(RequestBody, Encoding.UTF8, "application/json");

        var response = client.PostAsync(requestUri, content).Result;
        if (!response.IsSuccessStatusCode)  // it never gets in here since an exception is thrown
        {
            throw new HttpException(500, "PhantomJS status request failed");
        }
    }
    catch (Exception ex)
    {
        throw new Exception("PhantomJS status request failed", ex);
    }
}

0 个答案:

没有答案