2

当我使用 ObjectContent 对象创建 HttpContent 以通过 HttpClient 向 Web API 服务发送请求时,我收到以下错误:

无法将比配置的最大缓冲区大小更多的字节写入缓冲区:65536

以下代码用于发送请求。Card 对象有大约 15 个属性。

var client = new HttpClient();
var content = new ObjectContent<IEnumerable<Card>>(cards, "application/xml");
MessageBox.Show(content.ReadAsString());  //This line gives me the same error.

var response = client.Post("http://localhost:9767/api/cards", content);

如何将配置的大小更改为大于 65,536?

4

3 回答 3

2

Since the problem resides in the ReadAsString extension method I would suggest that you create your own extension method to solve the maximum buffer size issue.

Here’s an example of a ReadAsLargeString extension method that maybe solves the problem.

public static string ReadAsLargeString(this HttpContent content)
{
    var bufferedContent = new MemoryStream();
    content.CopyTo(bufferedContent);

    if (bufferedContent.Length == 0)
    {
        return string.Empty;
    }

    Encoding encoding = DefaultStringEncoding;
    if ((content.Headers.ContentType != null) && (content.Headers.ContentType.CharSet != null))
    {
        encoding = Encoding.GetEncoding(content.Headers.ContentType.CharSet);
    }

    return encoding.GetString(bufferedContent.GetBuffer(), 0, (int)bufferedContent.Length);
}
于 2011-11-03T08:59:24.217 回答
1

有一个关于这个的线程。尝试使用 HttpCompletionOption.ResponseContentRead:

var message = new HttpRequestMessage(HttpMethod.Post, "http://localhost:9767/api/cards");
message.Content = content; 
var client = new HttpClient();
client.Send(message, HttpCompletionOption.ResponseContentRead);
于 2011-11-02T15:48:00.600 回答
0

为客户试试这个:

HttpClient client = new HttpClient("http://localhost:52046/");

// enable support for content up to 10 MB size
HttpClientChannel channel = new HttpClientChannel() {
    MaxRequestContentBufferSize = 1024 * 1024 * 10 
};

client.Channel = channel;

在服务器上(片段基于预览 4,但您应该得到线索):

public class CustomServiceHostFactory : HttpConfigurableServiceHostFactory {
    public override ServiceHostBase CreateServiceHost(string constructorString, Uri[] baseAddresses) {
        var host = base.CreateServiceHost(constructorString, baseAddresses);

        foreach (HttpEndpoint endpoint in host.Description.Endpoints) {
            endpoint.TransferMode = TransferMode.Streamed;
            endpoint.MaxReceivedMessageSize = 1024 * 1024 * 10;
        }

        return host;
    }
}
于 2011-11-02T20:14:37.597 回答