我正在使用HttpClientPUT数据到HTTP服务器PutAsync.
当服务器发回错误代码(例如401 Unauthorized)时,它会关闭连接(在响应中提供了Connection:close标头).当发生这种情况时,HttpClient会抛出System.Net.Http.HttpRequestException(将内容复制到流时出错),并列出下面列出的内部异常.这似乎与写入数据有关(尽管事实上它在BeginRead中),因为如果我说服服务器读取所有正在发送的数据,则不会抛出异常.
我可以通过使用HttpClient.SendAsync与HttpCompletionOption.ResponseHeadersRead参数执行相同的任务来解决此问题.在这种情况下,不抛出异常,我可以阅读HttpResponseMessage.StatusCode.
我的问题是,异常是正确的吗?即,服务器没有遵循标准,关闭连接而不读取它不需要的所有数据?如果没有,那么是否存在问题,PutAsync因为StatusCode在这种情况下它不允许访问返回?
示例代码:
using (FileStream stream = File.OpenRead(FilePath))
using (StreamContent content = new StreamContent(stream))
using (HttpRequestMessage req = new HttpRequestMessage
{
Method = HttpMethod.Put,
RequestUri = new Uri(baseUri, Path),
Content = content,
})
using (HttpClient client = new HttpClient())
{
req.Content.Headers.ContentType = new MediaTypeHeaderValue(FileContentType);
// This version works:
//using (HttpResponseMessage resp = await client.SendAsync(req,
// HttpCompletionOption.ResponseHeadersRead))
// This version throws an exception:
using …Run Code Online (Sandbox Code Playgroud)