.Net Core api 长 运行 请求

.Net Core api long running request

我有一个 Web 应用调用 .Net Core API 来生成 PDF 文档。我正在进行大量 HTML 到 pdf 的转换,因此需要一段时间才能完成 200 页的文档。我让它在我的本地工作但不是我的 AppService。 起初,如果我超过 100 页(小页集有效),我会得到 "The specified CGI application encountered an error and the server terminated the process."。

调用我的代码api:

var httpClient = new HttpClient();
HttpContent content = new StringContent(JsonConvert.SerializeObject(pdfRecipeDto), Encoding.UTF8, "application/json");
httpClient.Timeout = System.TimeSpan.FromMinutes(30);
var pdfFileUrl = httpClient.PostAsync("http://yada-yada.azurewebsites.net/api/pdf/Generate", content)
                 .GetAwaiter()
                 .GetResult()
                 .Content.ReadAsStringAsync().Result; // yes i know this is gross

我找到了这个 和其他说类似的。尝试了第一个答案,但是在 Kudu 中手动修改了我的 web.config 之后(因为我不知道如何在我的项目中设置它)

<?xml version="1.0" encoding="utf-8"?>
 <configuration>
  <system.webServer>
    <handlers>
     <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified"/>
    </handlers>
    <aspNetCore requestTimeout="00:20:00"  processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="false"/>
  </system.webServer>
</configuration>

requestTimeout="00:20:00" 是重要的部分。

但我收到“500 - 请求超时。Web 服务器未能在指定时间内响应。”。

我也尝试将 .UseKestrel(...) 添加到我的 program.cs

public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
    .UseApplicationInsights()
            .UseStartup<Startup>()
            .UseKestrel(o =>
            {
                o.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(30);
            })
            .Build();;

但这似乎什么也没做。

原来 Azure App Service 有一个硬编码的 230 秒 请求规则。即使您对 web.config and/or startup.cs 进行了更改。

我在这里找到了答案: 并且 https://social.msdn.microsoft.com/Forums/en-US/17305ddc-07b2-436c-881b-286d1744c98f/503-errors-with-large-pdf-file?forum=windowsazurewebsitespreview

是的,Azure 负载均衡器的默认空闲超时设置约为四分钟,在此处的常见问题解答中有记录:https://docs.microsoft.com/en-us/azure/app-service/app-service-web-availability-performance-application-issues-faq#why-does-my-request-time-out-after-230-seconds

问:为什么我的请求在 230 秒后超时?

A​​zure 负载均衡器的默认空闲超时设置为四分钟。这通常是 Web 请求的合理响应时间限制。如果您的 Web 应用需要后台处理,我们建议使用 Azure WebJobs。 Azure Web 应用程序可以调用 WebJobs 并在后台处理完成时收到通知。您可以从多种使用 WebJobs 的方法中进行选择,包括队列和触发器。 WebJobs 专为后台处理而设计。您可以在 WebJob 中进行任意多的后台处理。 你可以使用 webjob 来完成你的任务,看看它是如何进行的。

此外,所有 Azure Web 应用程序(以及移动 App/Services、WebJobs 和 Functions)运行 都在称为沙箱的安全环境中。每个应用程序 运行 都在自己的沙箱中,将其执行与同一台机器上的其他实例隔离开来,并提供额外的安全性和隐私性,否则将无法获得。 查看 GitHub 页面 https://github.com/projectkudu/kudu/wiki/Azure-Web-App-sandbox#unsupported-frameworks,其中列出了 Azure 应用服务支持和不支持的 PDF 生成器。