设置ObjectContent Web API预览的最大大小5

时间:2011-11-02 14:10:27

标签: asp.net-mvc-3 wcf-web-api

当我使用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的大小?

3 个答案:

答案 0 :(得分:2)

由于问题存在于ReadAsString扩展方法中,我建议您创建自己的扩展方法来解决最大缓冲区大小问题。

这是一个可能解决问题的ReadAsLargeString扩展方法的示例。

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

答案 1 :(得分:1)

有一个thread。尝试使用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);

答案 2 :(得分: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;
    }
}