尝试使用HttpClient上传文件时,Web Api的RequestEntityTooLarge响应

时间:2014-11-03 09:08:00

标签: c# asp.net-web-api http-status-code-404 httpclient

我试图通过Post with Asp.Net Web Api创建一个上传文件的Web服务。这些分别是Client和Web Api的实现:

客户端:

using (var client = new HttpClient()) {
    client.BaseAddress = new Uri("https://127.0.0.1:44444/");
    using (var content =
       new MultipartFormDataContent("Upload----" + DateTime.Now.ToString(CultureInfo.InvariantCulture))) {
       content.Add(new ByteArrayContent(File.ReadAllBytes(filepath)));
       content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
       var response = await client.PostAsync("api/Synchronization", content);

       if (response.IsSuccessStatusCode)
           eventLog1.WriteEntry("Synchronization has been successful", EventLogEntryType.Information);
       else 
           eventLog1.WriteEntry(response.StatusCode + ":" + response.ReasonPhrase, EventLogEntryType.Error);

      }
}

服务器:

public class SynchronizationController : ApiController {

    public HttpResponseMessage SynchronizeCsv() {
        var task = this.Request.Content.ReadAsStreamAsync();
        task.Wait();
        Stream requestStream = task.Result;

        try {
            Stream fileStream = File.Create(HttpContext.Current.Server.MapPath(path));
            requestStream.CopyTo(fileStream);
            fileStream.Close();
            requestStream.Close();
        }
        catch (IOException) {
            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "A generic error occured. Please try again later.");
        }

        HttpResponseMessage response = new HttpResponseMessage();
        response.StatusCode = HttpStatusCode.Created;
        return response;
    }
}

的Web.config:

<system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" maxRequestLength="2097152" />
  </system.web>
  <system.webServer>
    <security>
      <requestFiltering>
        <requestLimits maxAllowedContentLength="2147483648" />
      </requestFiltering>
    </security>
    <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
  </system.webServer>

我尝试上传一个5Mb的文件,每次尝试调用该服务时,都会得到413 Http错误请求实体太大。如果文件很小(例如40kb),一切正常。

通过互联网查看我试图对web.config进行一些修改,但似乎没有任何工作正常。我做错了什么?

1 个答案:

答案 0 :(得分:8)

我通过此解决方案解决了问题:http://www.smartdigitizers.com/net-development-tips/iis-7-how-to-resolve-error-https-413-request-entity-too-large/

  1. 启动“Internet信息服务(IIS)管理器”
  2. 选择您在其下托管Web应用程序的网站。
  3. 在“功能”部分中,双击“配置编辑器”
  4. 在“Section”下,选择:system.webServer,然后选择serverRuntime
  5. 将“uploadReadAheadSize”部分修改为20MB(以字节为单位的值)
  6. 点击“应用”