简体   繁体   English

仅当文件大小很大时,使用PostAsync的WebAPI才会引发异常

[英]WebAPI using PostAsync throws exception only when filesize is large

I am trying to send a file to a WebAPI controller that does some processing with the file on a server. 我正在尝试将文件发送到WebAPI控制器,该服务器对服务器上的文件进行一些处理。 Everything seems to work well until I tried files that are large than 2mb... files large than this seem to be throwing an odd exception. 直到我尝试了大于2mb的文件,一切似乎都工作良好。大于此大小的文件似乎引发了奇怪的异常。

Here is the snippet: 这是代码段:

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

The exception is thrown on the line: 在行上抛出异常:

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

and is: 并且是:

No MediaTypeFormatter is available to read an object of type 'Object' from content with media type 'text/html'

It's not even hitting the breakpoint at the beginning of my service controller so I didnt include that code(although I can if thats potentially an issue). 它甚至没有达到服务控制器开始处的断点,因此我没有包含该代码(尽管如果那可能是一个问题,我可以这样做)。 As I said above, this ONLY happens with files > 2mb -- small files work just fine(thank god so I have something to show for a demo ^^). 就像我在上面说的那样,这仅在文件大于2mb时发生-小文件可以正常工作(感谢上帝,所以我有一些要演示的东西^^)。

Anyhelp with this would be greatly appreciated. 任何帮助,将不胜感激。

Cory's observation is right that Web API doesn't have a in-built formatter to either serialize or deserialize text/html content. Cory的观察是对的,Web API没有内置的格式化程序来序列化或反序列化text / html内容。 My guess is that you are most probably getting an error response in html. 我的猜测是,您很可能在html中收到错误响应。 If its indeed that, you can do the following: 如果确实如此,则可以执行以下操作:

When uploading files to a IIS hosted Web API application, you need to take care of the following stuff. 将文件上传到IIS托管的Web API应用程序时,需要注意以下事项。

You need to look for the following 2 settings in Web.config to increase the upload size: 您需要在Web.config中查找以下2个设置以增加上载大小:

NOTE(maxRequestLength="size in Kilo bytes") : 注意(maxRequestLength =“以千字节为单位的大小”)

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

NOTE(maxAllowedContentLength is in bytes) : 注意(maxAllowedContentLength以字节为单位)

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

Also note that the default buffer policy of Web API in IIS hosted scenarios is buffered , so if you are uploading huge files, your request would be consuming lot of memory. 另请注意,在IIS托管方案中,Web API的默认缓冲策略是buffered ,因此,如果您上传大文件,则您的请求将占用大量内存。 To prevent that you can change the policy like the following: 为防止这种情况,您可以像下面这样更改策略:

config.Services.Replace(typeof(IHostBufferPolicySelector), new CustomBufferPolicySelector());  

//---------------  

public class CustomBufferPolicySelector : WebHostBufferPolicySelector
{
    public override bool UseBufferedInputStream(object hostContext)
    {
        return false;
    }
}

The response is coming back with a text/html Content-Type, and ReadAsAsync<object>() doesn't know how to deserialize text/html into an object . 响应以text/html Content-Type返回,并且ReadAsAsync<object>()不知道如何将text/html反序列化为object

Likely, your web app is configured to only accept files up to a certain size and is returning an error with a friendly HTML message. 您的网络应用可能已配置为仅接受最大大小的文件,并通过友好的HTML消息返回错误。 You should be checking the response code before trying to deserialize the content: 在尝试反序列化内容之前,您应该检查响应代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM