[英]Set default page in ASP.NET Core 3.1 MVC+Razor Pages+Web API
[英]Asp.net core 3.1 with Razor Pages redirects to the Index page instead of the intended page
我的項目中的 Razor 頁面結構如下:
大多數內容都可以在“索引”頁面中找到。 我正在本地主機上處理我的本地 IIS。 當我在瀏覽器中鍵入本地主機地址時,索引頁面將按預期顯示。 但是,如果我鍵入 https://localhost:44352/Logout 以打開 Logout 頁面,它會調用 Index 頁面的 OnGet 方法並打開該頁面,而不是調用 Logout 頁面的 OnGet 方法。
下面是 Index 頁面的 OnGet 方法:
public async Task<IActionResult> OnGetAsync()
{
if (HttpContext.Session.GetString("activeModal") != null)
{
if (string.IsNullOrEmpty(HttpContext.Session.GetString("showModalOnGet")) == false && HttpContext.Session.GetString("showModalOnGet") == "true")
{
HttpContext.Session.SetString("showModalOnGet", "false");
}
else
{
HttpContext.Session.SetString("activeModal", "");
HttpContext.Session.SetString("loginStatusColor", "");
HttpContext.Session.SetString("loginStatusMessage", "");
HttpContext.Session.SetString("forgottenPassStatusColor", "");
HttpContext.Session.SetString("forgottenPassStatusMessage", "");
}
}
await ReloadData();
return null;
}
注銷 OnGet 的代碼:
public async Task<IActionResult> OnGetAsync()
{
await LogOutUser();
return RedirectToPage("Index");
}
兩個頁面都沒有在 @page 指令之后指定路由。 他們的構造函數沒有什么特別的。
這是 Startup.cs class 中的代碼:
public void ConfigureServices(IServiceCollection aServices)
{
Log.Information("Configuring Services");
/// Add caching of the static files
aServices.AddResponseCaching();
/// Add support for Razor
aServices.AddRazorPages();
aServices.Configure<CookiePolicyOptions>(options =>
{
/// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => false;
options.MinimumSameSitePolicy = SameSiteMode.None;
options.Secure = CookieSecurePolicy.Always;
});
/// Add the database connection
string lConnectionString = mEnvironment.IsDevelopment() ? "LocalDB" : "ServerDB";
aServices.AddDbContext<DB_Spa_WellnessContext>(options =>
{
options.UseSqlServer(mConfiguration.GetConnectionString(lConnectionString));
});
/// Add session to store data
/// Use memory cache for the session
aServices.AddDistributedMemoryCache();
aServices.AddSession(options =>
{
options.Cookie.Name = ".Spa_Wellness.Session";
options.IdleTimeout = TimeSpan.FromMinutes(2.0);
});
/// Add the configuration of the email client
aServices.AddSingleton<IEmailConfiguration>(mConfiguration.GetSection("EmailConfiguration").Get<XEmailConfiguration>());
/// Add the Email Service
aServices.AddTransient<IEmailService, XEmailService>();
// Add the configuration of the security service
aServices.AddSingleton<ISecurityConfiguration>(mConfiguration.GetSection("SecurityConfiguration").Get<XSecurityConfiguration>());
// Add the Security Service
aServices.AddTransient<ISecurityService, XSecurityService>();
/// Add the configuration of the Google Invisible Captcha
string lCaptchaSection = mEnvironment.IsDevelopment() ? "GoogleInvisibleCaptchaDev" : "GoogleInvisibleCaptcha";
aServices.AddSingleton<ICaptchaKeys>(mConfiguration.GetSection(lCaptchaSection).Get<XGoogleInvisibleCaptchaKeys>());
/// Add the service for obtaining user IP and cookies
aServices.AddHttpContextAccessor();
aServices.TryAddSingleton<IActionContextAccessor, ActionContextAccessor>();
/// HTML minification (https://github.com/Taritsyn/WebMarkupMin)
aServices
.AddWebMarkupMin(options =>
{
options.AllowMinificationInDevelopmentEnvironment = true;
options.DisablePoweredByHttpHeaders = true;
})
.AddHtmlMinification(options =>
{
options.MinificationSettings.RemoveOptionalEndTags = false;
options.MinificationSettings.WhitespaceMinificationMode = WhitespaceMinificationMode.Safe;
});
aServices.AddSingleton<IWmmLogger, WmmNullLogger>(); // Used by HTML minifier
/// Minification with WebOptimizer (https://github.com/ligershark/WebOptimizer)
aServices.AddWebOptimizer(pipeline =>
{
pipeline.MinifyJsFiles();
pipeline.MinifyCssFiles();
});
}
public static void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
/// Taken from MiniBlog to disable sniffing
app.Use((context, next) =>
{
context.Response.Headers.Add("X-Xss-Protection", "1");
context.Response.Headers.Add("X-Content-Type-Options", "nosniff");
context.Response.Headers.Add("X-Frame-Options", "DENY");
context.Response.Headers.Add(
"Content-Security-Policy",
"form-action 'self'; ");
/// Cache control
context.Response.GetTypedHeaders().CacheControl =
new Microsoft.Net.Http.Headers.CacheControlHeaderValue()
{
Public = true,
MaxAge = TimeSpan.FromDays(365)
};
context.Response.Headers[Microsoft.Net.Http.Headers.HeaderNames.Vary] =
new string[] { "Accept-Encoding" };
return next();
});
/// Minification with WebOptimizer (https://github.com/ligershark/WebOptimizer)
app.UseWebOptimizer();
/// Always redirect to HTTPS
app.UseHttpsRedirection();
/// Use static files and caching
app.UseStaticFiles();
app.UseRouting();
// app.UseResponseCaching();
app.UseCookiePolicy();
app.UseSession();
/// HTML minification (https://github.com/Taritsyn/WebMarkupMin)
/// TODO: Send web page to the developer
app.UseWebMarkupMin();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapRazorPages();
});
}
我不知道您是否有任何其他代碼片段可能感興趣。
另一個有趣的部分是 ControlPanel 文件夾中的頁面顯示沒有任何問題。 錯誤和隱私頁面也可以正常工作。 問題似乎出在新添加的頁面上。
我注意到的另一件事。 如果我在索引頁面上使用查詢字符串,查詢字符串的結果是 null,而不是獲取在瀏覽器中鍵入的內容。
忘了說有時會打開 Logout 頁面並調用其 OnGet 方法,但大多數時候會打開 Index 頁面。
我感覺我的啟動配置有問題,但是什么。
首先,確保索引頁面與 OnGetAsync 方法位於同一 controller 內。 如果沒有,我建議使用RedirectToAction("Action", "Controller");
.
我希望我有所幫助。
在花了更多時間調試后,我發現了導致問題的原因。 Startup.cs 中的以下代碼似乎是問題所在:
app.Use((context, next) =>
{
context.Response.Headers.Add("X-Xss-Protection", "1");
context.Response.Headers.Add("X-Content-Type-Options", "nosniff");
context.Response.Headers.Add("X-Frame-Options", "DENY");
context.Response.Headers.Add(
"Content-Security-Policy",
"form-action 'self'; ");
/// Cache control
/*context.Response.GetTypedHeaders().CacheControl =
new Microsoft.Net.Http.Headers.CacheControlHeaderValue()
{
Public = true,
MaxAge = TimeSpan.FromDays(365)
};
context.Response.Headers[Microsoft.Net.Http.Headers.HeaderNames.Vary] =
new string[] { "Accept-Encoding" };*/
return next();
});
我評論的最后幾行似乎導致了這個問題。 在我將它們注釋掉之后,一切正常(現在)。 我假設這里的一些緩存導致服務器返回索引頁面而不是注銷頁面。
無論如何,現在一切正常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.