c# - 文件上传错误 WCF WEB API(预览版 6): Cannot write more bytes to the buffer than the configured maximum buffer size: 65536

标签 c# asp.net wcf httpclient wcf-web-api

我在使用 WCF web api 时遇到了一个真正的问题。

我有一个上传文件并保存到磁盘的简单方法。我似乎已经设置了所有正确的参数,但是当我尝试上传一个 2mb 的文件时收到上述错误消息。

服务器代码:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    HttpServiceHostFactory _factory  = new HttpServiceHostFactory();

    var config = new HttpConfiguration() 
    { 
        EnableTestClient = true, 
        IncludeExceptionDetail = true,
        TransferMode = System.ServiceModel.TransferMode.Streamed,
        MaxReceivedMessageSize = 4194304,
        MaxBufferSize = 4194304    
    };

    _factory.Configuration = config;

    RouteTable.Routes.Add(new ServiceRoute("api/docmanage", _factory, typeof(WorksiteManagerApi)));
}

客户:

HttpClientHandler httpClientHandler = new HttpClientHandler();
httpClientHandler.MaxRequestContentBufferSize = 4194304;

var byteArray = 
    Encoding.ASCII.GetBytes(ConnectionSettings.WebUsername + ":" + ConnectionSettings.WebPassword);

HttpClient httpClient = new HttpClient(httpClientHandler);
httpClient.DefaultRequestHeaders.Authorization = 
    new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
httpClient.BaseAddress = new Uri(ConnectionSettings.WebApiBaseUrl);
httpClient.MaxResponseContentBufferSize = 4194304;

...

multipartFormDataContent.Add(new FormUrlEncodedContent(formValues));
multipartFormDataContent.Add(byteArrayContent);

var postTask = httpClient.PostAsync("api/docmanage/UploadFile", multipartFormDataContent);

然后,在服务器上:

[WebInvoke(Method = "POST")]
public HttpResponseMessage UploadFile(HttpRequestMessage request)
{
    // Verify that this is an HTML Form file upload request
    if (!request.Content.IsMimeMultipartContent("form-data"))
    {
        throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
    }

    // Create a stream provider for setting up output streams
    MultipartFormDataStreamProvider streamProvider = new MultipartFormDataStreamProvider();

    // Read the MIME multipart content using the stream provider we just created.
    IEnumerable<HttpContent> bodyparts = request.Content.ReadAsMultipart(streamProvider);

    foreach (var part in bodyparts)
    {
        switch (part.Headers.ContentType.MediaType)
        {
            case "application/octet-stream":
                if (part.Headers.ContentLength.HasValue)
                {
                    // BLOWS UP HERE:            
                    var byteArray = part.ReadAsByteArrayAsync().Result;

                    if (null == fileName)
                    {
                        throw new HttpResponseException(HttpStatusCode.NotAcceptable);
                    }
                    else
                    {
                        uniqueFileId = Guid.NewGuid().ToString();
                        string tempFilename = Path.GetTempPath() + @"\" + uniqueFileId + fileName;

                        using (FileStream fileStream = File.Create(tempFilename, byteArray.Length))
                        {
                            fileStream.Write(byteArray, 0, byteArray.Length); 
                        }
                    }

                }
                break;
        }
    }
}

有什么想法吗?我正在使用最新的 web api 预览....我注意到支持文档中缺少很多内容,但似乎有一些缓冲区限制我无法找到如何指定或被忽略.... .

最佳答案

HttpContent 类的(缺乏)文档中没有明确说明的一件事是默认内部缓冲区为 64K,因此一旦内容超过,任何非流的内容都会抛出您看到的异常64Kb。

解决方法是使用以下方法:

part.LoadIntoBufferAsync(bigEnoughBufferSize).Result();
var byteArray = part.ReadAsByteArrayAsync().Result;

我假设 HttpContent 类缓冲区的 64K 限制是为了防止服务器上发生过多的内存分配。我想知道将字节数组内容作为 StreamContent 传递是否会更好?这样它应该仍然可以工作,而不必增加 HttpContent 缓冲区大小。

关于c# - 文件上传错误 WCF WEB API(预览版 6): Cannot write more bytes to the buffer than the configured maximum buffer size: 65536,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9065223/

相关文章:

c# - HttpWebResponse.LastModified 的默认值

c# - 使某些行在 ViewModel 的 DataGrid 中不可选择

c# - 为什么我会得到这个 XML block 的 org.xml.sax.SAXException?

asp.net - 是否可以在ASP.NET中更改单个页面的网页超时阈值?

WCF REST 服务 : InstanceContextMode. PerCall 不工作

c# - WCF 的多态服务

c# - 如何杀死一个C#进程?

c# - 如何更改实例化对象(克隆)的位置?

asp.net - ASP.NET 5 中的应用程序见解

c# - 读取 XML 数据时已超出最大字符串内容长度配额 (8192)