我在使用 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/