You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 8中OnActionExecuted到视图渲染启动存在4秒以上延迟问题

.NET 8项目视图加载延迟排查求助

我明白这问题涉及诸多环节,但还是想发帖寻求技术思路。我的.NET 8项目存在视图加载缓慢的问题:控制器代码执行仅耗时约12ms,但从控制器代码完成(OnActionExecuted,时间为2024年7月23日下午3:17:08)到视图开始加载(RenderBegin,时间为2024年7月23日下午3:17:14),始终存在4-6秒的延迟。以下是Program.cs的代码:

var builder = WebApplication.CreateBuilder(args);
connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");

// 从配置文件(appsettings.json)获取scopes
var initialScopes = builder.Configuration.GetValue<string>("DownstreamApi:Scopes")?.Split(' ');
// 向容器添加服务
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"))
    .EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
    .AddMicrosoftGraph(builder.Configuration.GetSection("DownstreamApi"))
    .AddInMemoryTokenCaches();

builder.Services.AddFeatureManagement();
builder.Services.AddScoped<PreserveStateFilter>();
builder.Services.AddHangfire(configuration => configuration
       .SetDataCompatibilityLevel(CompatibilityLevel.Version_180)
       .UseSimpleAssemblyNameTypeSerializer()
       .UseRecommendedSerializerSettings()
       .UseSqlServerStorage(connectionString));
builder.Services.AddControllersWithViews(options =>
{
    var policy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .Build();
    options.Filters.Add(new AuthorizeFilter(policy));
}).AddRazorOptions(opt => {
    opt.ViewLocationFormats.Add("/Views/Forms/{0}" + RazorViewEngine.ViewExtension);
    opt.ViewLocationFormats.Add("/Views/ArchivedForms/{0}" + RazorViewEngine.ViewExtension);
});

builder.Services.AddSession(options => {});
builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

builder.Services.AddHangfireServer();

builder.Services.AddRazorPages()
    .AddMicrosoftIdentityUI();

var app = builder.Build();

// 配置HTTP请求管道
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // 默认HSTS有效期为30天,生产环境可根据情况调整
    app.UseHsts();
}
Serilog.Log.Logger = new LoggerConfiguration()
      .ReadFrom.Configuration(app.Configuration)
     .WriteTo.MSSqlServer(
         connectionString: connectionString,
         sinkOptions: new MSSqlServerSinkOptions
         {
             TableName = "Log",
             AutoCreateSqlTable = true
         })
     .CreateLogger();        

// 向辅助函数添加配置以允许访问应用设置
BaseModel.AppSettingsConfigure(app.Services.GetRequiredService<IConfiguration>());
FormsPortal.AppSettingsConfigure(app.Services.GetRequiredService<IConfiguration>());
HelperFunctions.AppSettingsConfigure(app.Services.GetRequiredService<IConfiguration>());
EmailUtility.AppSettingsConfigure(app.Services.GetRequiredService<IConfiguration>());
FormsJob.AppSettingsConfigure(app.Services.GetRequiredService<IConfiguration>());
app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();
app.UseSession();
app.UseAuthorization();
app.Use(async (context, next) =>
{
    if (context.Request.Path.Equals("/hangfire", StringComparison.OrdinalIgnoreCase)
        && !context.User.Identity.IsAuthenticated)
    {
        await context.ChallengeAsync();
        return;
    }

    await next();
});
app.UseHangfireDashboard("/hangfire", new DashboardOptions()
{
    AppPath = "/Forms",
    Authorization = new[] { new HangfireAuthorizationFilter() },
    IgnoreAntiforgeryToken = true

});

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{encryptedId?}");
app.MapRazorPages();
app.StartRecurringJobs();
app.Run();

内容的提问来源于stack exchange,提问作者jay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 16:58:14