其他分享
首页 > 其他分享> > HttpResponseException为什么只允许异步读取其消息?

HttpResponseException为什么只允许异步读取其消息?

作者:互联网

我正在编写一个单元测试方法,该方法将练习在我的测试条件下会引发带有特定响应消息的HttpResponseException的代码.

我的测试方法代码的相关部分如下所示:

try
{
    MyClassBeingTested.MyWebServiceMethodBeingTested(myParameters);
}
catch (HttpResponseException ex)
{
    string errorMessage = await ex.Response.Content.ReadAsStringAsync();
    Assert.IsTrue(errorMessage.Contains("My expected error message string"));
    return;
}
Assert.Fail("Expected HttpResponseException didn't get thrown");

此代码有效,并且测试通过.

但是,我想更好地了解理解为什么读取错误消息的代码需要以这种方式构造. HttpResponseException类仅提供对其消息的异步访问.因此,我需要通过ReadAsStringAsync()获取消息,而不是仅仅能够通过执行诸如ex.Response.Content.Message之类的操作来同步获取消息.

我觉得我可能会缺少有关HttpResponseException类为何以这种方式工作的信息. HttpResponseException不提供对其响应消息的同步访问的原因是什么?

解决方法:

The HttpResponseException class only provides async access to its message.

HttpResponseException为您提供对HTTP响应消息(Response)的同步访问,它为您提供对其内容(Content)的同步访问. HTTP流的内容是始终异步读取的内容.在某些用途中,HTTP流的内容在使用时已完全存在于内存中.在其他用途​​中,HTTP流的内容通过网络进行流传输.

例如,如果您使用HttpCompletionOption.ResponseHeadersRead发出HTTP请求,那么响应内容将被流式传输,并且有可能在响应的内容实际到达运行代码的框之前检查状态代码并引发异常.

标签:system-web,c
来源: https://codeday.me/bug/20191025/1931150.html