Skip to main content
 首页 » 编程设计

c#之仅当文件大时,使用 PostAsync 的 Web API 才会抛出异常

2024年02月13日30qlqwjy

我正在尝试将文件发送到 WebAPI Controller ,该 Controller 对服务器上的文件进行一些处理。在我尝试大于 2mb 的文件之前,一切似乎都运行良好……比这大的文件似乎会抛出一个奇怪的异常。

这是片段:

       var progress = new ProgressMessageHandler(); 
        progress.HttpSendProgress += ProgressEventHandler; 
        HttpClient client = HttpClientFactory.Create(progress); 
        client.Timeout = TimeSpan.FromMinutes(20); 
try   
                { 
                    using ( 
                        var fileStream = new FileStream(file, FileMode.Open,      FileAccess.Read, FileShare.Read, 1024, 
                        useAsync: true)) 
                { 
                    var content = new StreamContent(fileStream, 1024); 
                    var address = new Uri(string.Format("{0}api/File/Upload?submittalId={1}&fileName={2}&documentTypeId={3}", FileServiceUri, tabTag.submittalId, Path.GetFileName(file), documentTypeId)); 
                    client.MaxResponseContentBufferSize = 2147483647; 
                    var response = await client.PostAsync(address, content); 
                    var result = response.Content.ReadAsAsync<object>(); 
                    if (!response.IsSuccessStatusCode) 
                        continue; 
                } 

线上抛出异常:

var response = await client.PostAsync(address, content);

并且是:

没有 MediaTypeFormatter 可用于从媒体类型为“text/html”的内容中读取类型为“Object”的对象

它甚至没有在我的服务 Controller 开始时遇到断点,所以我没有包含该代码(尽管如果这可能是一个问题,我可以)。正如我上面所说,这只发生在文件 > 2mb 时——小文件工作正常(感谢上帝,所以我有一些东西可以展示给演示 ^^)。

如有任何帮助,我们将不胜感激。

请您参考如下方法:

Cory 的观察是正确的,即 Web API 没有内置的格式化程序来序列化或反序列化文本/html 内容。我的猜测是您很可能在 html 中收到错误响应。如果确实如此,您可以执行以下操作:

将文件上传到 IIS 托管的 Web API 应用程序时,您需要注意以下事项。

您需要在 Web.config 中查找以下 2 个设置以增加上传大小:

注意(maxRequestLength="以千字节为单位的大小"):

<system.web> <httpRuntime targetFramework="4.5" maxQueryStringLength="" maxRequestLength="" maxUrlLength="" /> 

注意(maxAllowedContentLength 以字节为单位):

<system.webServer> <security> <requestFiltering> <requestLimits maxAllowedContentLength="" maxQueryString="" maxUrl=""/> 

另请注意,IIS 托管方案中 Web API 的默认缓冲策略是 buffered,因此如果您正在上传大文件,您的请求将消耗大量内存。为防止这种情况发生,您可以更改如下政策:

config.Services.Replace(typeof(IHostBufferPolicySelector), new CustomBufferPolicySelector());   
 
//---------------   
 
public class CustomBufferPolicySelector : WebHostBufferPolicySelector 
{ 
    public override bool UseBufferedInputStream(object hostContext) 
    { 
        return false; 
    } 
}