首页 > 解决方案 > Azure 中 ASP.NET CORE WEBAPI 服务的初始响应缓慢 - Always On 已经为 True

问题描述

我有一个使用 Azure Active Directory 和 Azure SQL Server 在 Azure 中运行的 ASP.NET WEBAPI 服务。我已经进入 Azure 应用服务设置并打开了 Always On,但我确信 WEBAPI 正在卸载。

对于测试,我有一组通常需要 4-5 秒的调用。有时通话时间超过 30 秒。

除了这种偶尔的缓慢响应之外,没有任何问题。

WEBAPI 服务没有可查看的页面。仅限 API 控制器。

可能不相关,但我也使用 EF 进行数据访问。我也使用 CORS。

这是我的 Azure 应用设置:

[
  {
    "name": "ASPNETCORE_ENVIRONMENT",
    "value": "Development",
    "slotSetting": true
  },
  {
    "name": "BasePath",
    "value": "*****************************",
    "slotSetting": true
  },
  {
    "name": "WEBSITE_HTTPLOGGING_RETENTION_DAYS",
    "value": "7",
    "slotSetting": false
  },
  {
    "name": "WEBSITE_RUN_FROM_PACKAGE",
    "value": "1",
    "slotSetting": false
  }
]

这是 Azure 常规设置: 通用设置

这是我的大部分 StartUp.cs 文件:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<DatabaseContext>(options =>
        options.UseSqlServer(
            Configuration.GetConnectionString("DefaultConnection"), o =>
            {
                o.EnableRetryOnFailure();
            })
        .ConfigureWarnings(warnings => warnings.Ignore(Microsoft.EntityFrameworkCore.Diagnostics.CoreEventId.ContextInitialized))
        .EnableSensitiveDataLogging(true));

    services
        .AddAuthentication("Azure")
        .AddPolicyScheme("Azure", "Authorize AzureAd or AzureAdBearer", options =>
        {
            options.ForwardDefaultSelector = context =>
            {
                var authHeader = context.Request.Headers["Authorization"].FirstOrDefault();
                if (authHeader?.StartsWith("Bearer") == true)
                {
                    return JwtBearerDefaults.AuthenticationScheme;
                }
                return AzureADDefaults.AuthenticationScheme;
            };
        })
        .AddJwtBearer(opt =>
        {
            opt.Audience = Configuration["AAD:ResourceId"];
            opt.Authority = $"{Configuration["AAD:Instance"]}{Configuration["AAD:TenantId"]}";
        })
        .AddAzureAD(options => Configuration.Bind("AzureAd", options));


    var origins = Configuration.GetSection("AppSettings:AllowedOrigins").Value.Split(",");
    services.AddCors(o => o.AddPolicy(specificOrigins, builder =>
    {
        builder.WithOrigins(origins)
               .AllowAnyMethod()
               .AllowAnyHeader()
               .AllowCredentials()
               .SetIsOriginAllowed((host) => true);
    }));

    services.Configure<CookiePolicyOptions>(options =>
    {
        options.MinimumSameSitePolicy = SameSiteMode.Strict;
        options.HttpOnly = Microsoft.AspNetCore.CookiePolicy.HttpOnlyPolicy.Always;
        options.Secure = CookieSecurePolicy.Always;
    });
    services.AddResponseCaching();

    services.AddControllers();

    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    services.AddScoped<LogUserActivity>();
    services.AddSession();
    services.AddHttpContextAccessor();
    services.AddAutoMapper();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
    loggerFactory.AddSerilog();
    if (_currentEnvironment.IsDevelopment() || _currentEnvironment.IsEnvironment("LOCAL"))
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        app.UseHsts();
    }
    app.UseCors(specificOrigins);
    app.UseHttpsRedirection();
    app.UseSession();
    app.UseStaticFiles();

    app.UseRouting();

    app.UseResponseCaching();

    app.UseCookiePolicy();
    app.UseAuthentication();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
        endpoints.MapDefaultControllerRoute();
    });
}

标签: azureazure-web-app-serviceasp.net-core-webapi

解决方案


这个问题的答案应该是测试的过程。

根据官方的解释,我们可以看到。

在此处输入图像描述

测试步骤

  1. 创建一个测试 api,如下所示进行测试。

    public string test() {
        return "I'm test api.";
    }
    
  2. 插入计算每个步骤或代码行执行时间的代码

    例如:在 C# 中使用秒表

原因

官方永远在线应该没问题。建议通过测试代码,测试每一步都需要很长时间。

然后用被测试的api来测试在同样的条件下执行这段简单的代码是否还会出现你提到的现象。

问题的可能原因是连接数据库执行SQL,或者其他业务耗时较长,或者其他错误。记录耗时时间或通过ILogger输出查看。


推荐阅读