gpt4 book ai didi

c# - 尝试使用 HttpClient 上传文件时来自 Web Api 的 RequestEntityTooLarge 响应

转载 作者:太空宇宙 更新时间:2023-11-03 17:50:51 24 4
gpt4 key购买 nike

我正在尝试创建一个 Web 服务以使用 Asp.Net Web Api 通过 Post 上传文件。这些分别是 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;
}
}

网络配置:

<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 进行一些修改,但似乎没有任何工作正常。我做错了什么?

最佳答案

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

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

关于c# - 尝试使用 HttpClient 上传文件时来自 Web Api 的 RequestEntityTooLarge 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26710925/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com