我有 web api 项目。
我需要将带有文件的 json 数据作为编码的 base64 字符串(最多 200 mb)发布到那里。
如果我发送大约 10 MB 的数据,那么下一个方法通常会正确填充模型 ImportMultipleFileModel。
[HttpPost]
public async Task<HttpResponseMessage> ImportMultipleFiles(ImportMultipleFileModel importMultipleFileModel)
{
var response = ImportFiles(importFileModel);
return response;
}
如果我发送更多,则模型为空。
为什么?
所以我将方法签名更改为:
[HttpPost]
public async Task<HttpResponseMessage> ImportMultipleFiles()
{
ImportMultipleFileModel importMultipleFileModel = null;
var requestData = await Request.Content.ReadAsStringAsync();
try
{
JsonConvert.
importMultipleFileModel = JsonConvert.DeserializeObject<ImportMultipleFileModel>(requestData);
}catch(Exception e)
{ }
}
对于编码的 30 MB 文件,我通常将 requestData 作为 json 字符串获取。对于 60 mb,我得到空字符串。 为什么?
接下来我将方法更改为
[HttpPost]
public async Task<HttpResponseMessage> ImportMultipleFiles()
{
ImportMultipleFileModel importMultipleFileModel = null;
var requestData = Request.Content.ReadAsStringAsync().Result;
try
{
importMultipleFileModel = JsonConvert.DeserializeObject<ImportMultipleFileModel>(requestData);
}catch(Exception e)
{ }
}
并且由于 OutOfMemoryException 而导致反序列化失败。
为什么?
更新: maxRequestLength, maxAllowedContentLength 设置为 2147483647
最佳答案
尝试设置 maxRequestLength
.
<httpRuntime targetFramework="4.5" maxRequestLength="65536" />
或maxAllowedContentLength
(我总是搞不清哪个是哪个)。
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="52428800" />
</requestFiltering>
</security>
此外,我会重新考虑以这种方式发布数据。阅读this article form MSDN ,它主要针对 WCF,但我认为内容大部分是有效的。
The strategy to deal with large payloads is streaming.
最后一个例子的旁注;当您可以使用 await
时,您不应该(或者很少)使用 .Result
。 Stephen Cleary写了一个很好的答案here .
关于c# - 带有 json 的 asp web.api 的最大 http 请求大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38563118/