我知道这里有很多变化的部分需要考虑,但我想我应该发帖看看是否有人有任何想法。 我遇到了视图加载时间缓慢的问题。 我在控制器内的各个点添加了日志记录,控制器代码在大约 12 毫秒内执行。 所以我在视图的顶部添加了日志记录。 从我的控制器代码完成到视图开始加载始终有 4-6 秒的延迟:
OnActionExecuted - 7/23/2024 3:17:08 PM <- Last entry from end of ActionResult method.
渲染开始 - 7/23/2024 3:17:14 PM <- At the top of _Layout
这是来自 Program.cs 的代码:
var builder = WebApplication.CreateBuilder(args);
connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");
// Get the scopes from the configuration (appsettings.json)
var initialScopes = builder.Configuration.GetValue<string>("DownstreamApi:Scopes")?.Split(' ');
// Add services to the container.
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();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
Serilog.Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(app.Configuration)
.WriteTo.MSSqlServer(
connectionString: connectionString,
sinkOptions: new MSSqlServerSinkOptions
{
TableName = "Log",
AutoCreateSqlTable = true
})
.CreateLogger();
// Add configuration to helper functions to allow access to app settings
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();
长话短说,延迟是由应用于我的输入的 asp-for 标签引起的。 该项目生成表单并将表单/数据存储在 JSON 中(因此可以完成表单版本控制并且数据仍然匹配)。 因此,用于生成表单的许多信息都存储在隐藏字段中并随表单一起发回。 我们开始注意到一些较长表格上的问题。
表单越大,用于生成的 asp-for 标签就越多,从而导致加载延迟。 更改代码以进行迭代并使用索引来命名隐藏字段修复了加载时的长时间延迟。 特别是长形式从 5 秒加载到 < 500ms.