31

我想多次发送完全相同的请求,例如:

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);

第二次发送请求将抛出异常消息:

请求消息已发送。不能多次发送相同的请求消息。

他们是“克隆”请求的一种方式,以便我可以再次发送吗?

我的真实代码HttpRequestMessage在上面的示例中设置了更多变量,例如标头和请求方法等变量。

4

5 回答 5

24

我编写了以下扩展方法来克隆请求。

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;
}
于 2013-08-02T10:18:41.610 回答
21

这是对@drahcir 提出的扩展方法的改进。改进是确保克隆请求的内容以及请求本身:

public static HttpRequestMessage Clone(this HttpRequestMessage request)
{
    var clone = new HttpRequestMessage(request.Method, request.RequestUri)
    {
        Content = request.Content.Clone(),
        Version = request.Version
    };
    foreach (KeyValuePair<string, object> prop in request.Properties)
    {
        clone.Properties.Add(prop);
    }
    foreach (KeyValuePair<string, IEnumerable<string>> header in request.Headers)
    {
        clone.Headers.TryAddWithoutValidation(header.Key, header.Value);
    }

    return clone;
}

public static HttpContent Clone(this HttpContent content)
{
    if (content == null) return null;

    var ms = new MemoryStream();
    content.CopyToAsync(ms).Wait();
    ms.Position = 0;

    var clone = new StreamContent(ms);
    foreach (KeyValuePair<string, IEnumerable<string>> header in content.Headers)
    {
        clone.Headers.Add(header.Key, header.Value);
    }
    return clone;
}

编辑 05/02/18:这里是异步版本

public static async Task<HttpRequestMessage> CloneAsync(this HttpRequestMessage request)
{
    var clone = new HttpRequestMessage(request.Method, request.RequestUri)
    {
        Content = await request.Content.CloneAsync().ConfigureAwait(false),
        Version = request.Version
    };
    foreach (KeyValuePair<string, object> prop in request.Properties)
    {
        clone.Properties.Add(prop);
    }
    foreach (KeyValuePair<string, IEnumerable<string>> header in request.Headers)
    {
        clone.Headers.TryAddWithoutValidation(header.Key, header.Value);
    }

    return clone;
}

public static async Task<HttpContent> CloneAsync(this HttpContent content)
{
    if (content == null) return null;

    var ms = new MemoryStream();
    await content.CopyToAsync(ms).ConfigureAwait(false);
    ms.Position = 0;

    var clone = new StreamContent(ms);
    foreach (KeyValuePair<string, IEnumerable<string>> header in content.Headers)
    {
        clone.Headers.Add(header.Key, header.Value);
    }
    return clone;
}
于 2017-09-03T17:49:09.137 回答
13

我正在传递一个实例Func<HttpRequestMessage>而不是一个实例HttpRequestMessage。该 func 指向一个工厂方法,因此每次调用它时我都会收到一条全新的消息,而不是重复使用。

于 2013-08-19T17:00:53.330 回答
8

我有类似的问题,并以一种黑客的方式解决了它,反射。

感谢开源!通过阅读源代码,原来类中有一个私有字段_sendStatusHttpRequestMessage我所做的是0在重用请求消息之前将其重置为。它适用于 .NET Core,我希望微软不会永远重命名或删除它。:p

// using System.Reflection;
// using System.Net.Http;
// private const string SEND_STATUS_FIELD_NAME = "_sendStatus";
private void ResetSendStatus(HttpRequestMessage request)
{
    TypeInfo requestType = request.GetType().GetTypeInfo();
    FieldInfo sendStatusField = requestType.GetField(SEND_STATUS_FIELD_NAME, BindingFlags.Instance | BindingFlags.NonPublic);
    if (sendStatusField != null)
        sendStatusField.SetValue(request, 0);
    else
        throw new Exception($"Failed to hack HttpRequestMessage, {SEND_STATUS_FIELD_NAME} doesn't exist.");
}
于 2017-04-20T07:10:56.400 回答
0

AFAIK,HttpClient 只是 'HttpWebRequest' 的包装器,它使用流来发送/接收数据,因此无法重用请求,尽管克隆它/使其循环运行应该很简单。

于 2013-08-01T17:29:32.100 回答