应用程序作为 Linux systemd 服务运行时,HttpClient 响应太慢

问题描述 投票:0回答:1

我将应用程序托管在 Ubuntu 服务器上。 我有一个 API 端点可以通过 POST 请求调用外部 API。

  1. 在应用程序位置使用 Dotnet Run 运行应用程序时,我们在 2 秒内收到 API 响应。

  2. 将应用程序作为服务运行时,我们会在约 18 秒内收到响应

代码:

[HttpGet]
    [AllowAnonymous]
    [Route("TestCall")]
    public async Task<IActionResult> TestCall()
    {
        var dict = new Dictionary<string, string>();
        dict.Add("username", "admin");
        dict.Add("password", "P@55w0rd");
        dict.Add("grant_type", "password");
        var httpClientHandler = new HttpClientHandler();
        // httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, sslPolicyErrors) =>
        // {
        //     return true;
        // };
        httpClientHandler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
        httpClientHandler.CheckCertificateRevocationList = false;

        using var client = new HttpClient(httpClientHandler);
        using var req = new HttpRequestMessage(HttpMethod.Post, "https://thirdpartyapi.com/token") { Content = new FormUrlEncodedContent(dict) };
        Log.Information("Before Api Call"+DateTime.Now);
        var res =await client.SendAsync(req).ConfigureAwait(false);
        Log.Information("End Api Call"+DateTime.Now);
        return Ok(res.Content.ReadAsStringAsync().Result);
    }

服务

[Unit]
Description=Crystal App

[Service]
WorkingDirectory=/application/crystal
ExecStart=/usr/bin/dotnet /application/crystal/Crystal.API.dll --urls "http://localhost:5000"
Restart=always
# Restart service after 10 seconds if the dotnet service crashes:
RestartSec=10
KillSignal=SIGINT
SyslogIdentifier=Crystal
User=www-data
Environment=HTTP_PROXY=
Environment=ASPNETCORE_ENVIRONMENT=Production
c# linux dotnet-httpclient systemd
1个回答
0
投票

检查目录权限并尝试更改服务文件行中的用户

 User=www-data
,作者:
User=root

注意 - 测试完成后请不要使用 root 用户运行服务,您可以使用 www-data 用户运行服务,root 用户仅用于测试目的。

© www.soinside.com 2019 - 2024. All rights reserved.