重新发送的Htt prequestMessage - 异常 [英] Re-Send HttpRequestMessage - Exception

查看:930
本文介绍了重新发送的Htt prequestMessage - 异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想发完全相同的请求不止一次,例如:

I want to send the exact same request more than once, for example:

HttpClient client = new HttpClient();
HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Get, "http://example.com");

await client.SendAsync(req, HttpCompletionOption.ResponseContentRead);
await client.SendAsync(req, HttpCompletionOption.ResponseContentRead);

发送第二次请求将引发异常的消息:

Sending the request for a second time will throw an exception with the message:

请求消息已经发出。无法发送相同的请求   消息多次。

The request message was already sent. Cannot send the same request message multiple times.

是他们的一种方式的克隆的的要求,这样我可以重新发送?

Is their a way to "clone" the request so that I can send again?

我真正的code对设置更多的变量的Htt prequestMessage 比在上面的例子中,类似的报头和请求的方法变量。

My real code has more variables set on the HttpRequestMessage than in the example above, variables like headers and request method.

推荐答案

我写了下面的扩展方法克隆的要求。

I wrote the following extension method to clone the request.

public static HttpRequestMessage Clone(this HttpRequestMessage req)
{
    HttpRequestMessage clone = new HttpRequestMessage(req.Method, req.RequestUri);

    clone.Content = req.Content;
    clone.Version = req.Version;

    foreach (KeyValuePair<string, object> prop in req.Properties)
    {
        clone.Properties.Add(prop);
    }

    foreach (KeyValuePair<string, IEnumerable<string>> header in req.Headers)
    {
        clone.Headers.TryAddWithoutValidation(header.Key, header.Value);
    }

    return clone;
}

这篇关于重新发送的Htt prequestMessage - 异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆