ASP.NET Core 7 project takes long time on first load in production #54328
Replies: 4 comments
-
The only difference in your code between debug and release is the database connection string. |
Beta Was this translation helpful? Give feedback.
-
Hi,I checked the connection string,the database was ok.the problem is probably with the code or the server |
Beta Was this translation helpful? Give feedback.
-
Hi. It looks like this is a question about how to use ASP.NET Core. While we do our best to look through all the issues filed here, we are not a general-purpose forum. To get a faster response we suggest posting your questions to StackOverflow using the asp.net-core-mvc tag. |
Beta Was this translation helpful? Give feedback.
-
it seems it is a server problem |
Beta Was this translation helpful? Give feedback.
-
Description
I have an ASP.NET Core 7 Razor pages project. It works fine on localhost, but when I upload the project to my web server on the internet, the first time it loads, it takes a few seconds to load the website, however subsequent requests are fast.
Here is my program.cs file - is there something wrong with my code or the server?
Configuration
`using mywebsite.Data;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Mvc;
using System.Text.Json.Serialization;
using Microsoft.Net.Http.Headers;
using mywebsite.Core.Middleware;
using Keyvan1.Utility;
using AutoMapper;
using GoogleReCaptcha.V3.Interface;
using GoogleReCaptcha.V3;
var builder = WebApplication.CreateBuilder(args);
builder.WebHost
.CaptureStartupErrors(true)
.UseSetting("detailedErrors", "true");
builder.Services.Configure(options =>
{
options.Cookie.Name = "mywebsiteTempDataCookie";
});
builder.Services.AddControllersWithViews()
.AddJsonOptions(x => x.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles);
var keysDirectoryName = "Keys";
var keysDirectoryPath = Path.Combine(builder.Environment.ContentRootPath, keysDirectoryName);
if (!Directory.Exists(keysDirectoryPath))
{
Directory.CreateDirectory(keysDirectoryPath);
}
builder.Services.AddDataProtection()
.PersistKeysToFileSystem(new DirectoryInfo(keysDirectoryPath))
.SetApplicationName("mywebsite")
.SetDefaultKeyLifetime(TimeSpan.FromDays(30));
#if DEBUG
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext(options =>
options.UseSqlServer("Server=(local);Database=test;Trusted_Connection=True;TrustServerCertificate=True"));
#else
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext(options =>
options.UseSqlServer(connectionString));
#endif
builder.Services.AddDatabaseDeveloperPageExceptionFilter();
builder.Services.AddIdentity<ApplicationUser, IdentityRole>(config => {
config.SignIn.RequireConfirmedEmail = true;
config.User.RequireUniqueEmail = true;
// Password requirements
config.Password.RequireDigit = false;
config.Password.RequiredLength = 6;
// config.Password.RequiredUniqueChars = 1;
config.Password.RequireLowercase = true;
config.Password.RequireNonAlphanumeric = false;
config.Password.RequireUppercase = false;
})
.AddEntityFrameworkStores()
.AddDefaultTokenProviders();
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession(options =>
{
options.Cookie.Name = "mywebsite.Session";
options.IdleTimeout = TimeSpan.FromHours(24);
options.Cookie.IsEssential = true;
options.Cookie.HttpOnly = true;
});
builder.Services.Configure(options =>
{
options.CheckConsentNeeded = context => false;
options.MinimumSameSitePolicy = Microsoft.AspNetCore.Http.SameSiteMode.None;
});
builder.Services.AddAuthorization(options =>
{
options.AddPolicy(Constants.AdminRole, policy => policy.RequireRole(Constants.AdminRole));
});
builder.Services.ConfigureApplicationCookie(options =>
{
// options.Cookie.HttpOnly = true;
//options.Cookie.IsEssential = true;
options.Cookie.Name = "KeyhanStore";
options.ExpireTimeSpan = TimeSpan.FromDays(2);
options.SlidingExpiration = true;
options.LoginPath = $"/admin/Login";
options.LogoutPath = $"/admin/Logout";
options.AccessDeniedPath = $"/Areas/admin/AccessDenied";
});
builder.Services.AddRazorPages();
builder.Services.AddHttpContextAccessor();
builder.Services.AddCors(options => options.AddPolicy("Cors", builder =>
{
builder
.AllowAnyHeader()
.AllowAnyMethod()
//.AllowCredentials()
.WithHeaders("accept", "content-type", "origin")
.AllowAnyOrigin();
}));
builder.Services.Configure(builder.Configuration.GetSection("PhotoSettings"));
builder.Services.Configure(builder.Configuration.GetSection("EmailSettings"));
builder.Services.AddHttpClient<ICaptchaValidator, GoogleReCaptchaValidator>();
builder.Services.AddScoped<IUnitOfWork, UnitOfWork>();
builder.Services.AddScoped<IProductRepository, ProductRepository>();
builder.Services.AddTransient<IPhotoService, PhotoService>();
builder.Services.AddTransient<IPhotoStorage, PhotoStorage>();
builder.Services.AddTransient<IEmailService, EmailService>();
builder.Services.AddScoped<IStatsRepository, StatsRepository>();
builder.Services.AddScoped<IContactRepository, ContactRepository>();
builder.Services.AddScoped<ICategoryRepository, CategoryRepository>();
builder.Services.AddScoped<ISettingRepository, SettingRepository>();
builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
builder.Services.AddTransient<IDbInitializer, DbInitializer>();
builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
Mapper.Initialize(x =>
{
x.AddProfile();
});
builder.Services.AddMvc()
.AddRazorPagesOptions(options =>
{ options.Conventions.AuthorizeAreaFolder("admin", "/Products");
options.Conventions.AuthorizeAreaFolder("admin", "/Settings");
options.Conventions.AuthorizeAreaFolder("admin", "/Categories");
});
var app = builder.Build();
using (var scope = app.Services.CreateScope())
{
var services = scope.ServiceProvider;
var context = services.GetRequiredService();
context.Database.Migrate();
}
if (app.Environment.IsDevelopment())
{
app.UseMigrationsEndPoint();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseCors("Cors");
app.UseSecurityHeadersMiddleware(
new SecurityHeadersBuilder()
.AddDefaultSecurePolicy());
app.UseHttpsRedirection();
app.UseStaticFiles(new StaticFileOptions
{
OnPrepareResponse = ctx =>
{
const int durationInSeconds = 60 * 60 * 24;
ctx.Context.Response.Headers[HeaderNames.CacheControl] =
"public,max-age=" + durationInSeconds;
}
});
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseSession();
app.MapRazorPages();
#pragma warning disable ASP0014
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapAreaControllerRoute(
"admin",
"admin",
"admin/{controller=Home}/{action=Index}/{id?}");
endpoints.MapControllerRoute(
"default", "{controller=Home}/{action=Index}/{id?}");
});
#pragma warning restore ASP0014
app.Run();`
Beta Was this translation helpful? Give feedback.
All reactions