我有一個asp.net core 3.1 MVC專案。它添加了個人資訊。當我通常點擊一個按鈕進入登錄頁面或注冊頁面時,它能如期作業。但是當我在控制器上使用[Authorize]或者在Startup.cs檔案中使用全域授權過濾器時,該頁面并沒有重定向到登錄頁面。
這種情況下的重定向鏈接是
https://localhost:5001/Account/Login?ReturnUrl=/
那里的鏈接應該是
https://localhost:5001/Identity/Account/Login?ReturnUrl=/
如果你仔細觀察,我得到的鏈接中缺少區域名稱"身份"。我想我的Startup.cs檔案配置有問題,但無法找出原因。 我的專案中有Multiple Areas以及Identity
。Startup.cs
public Startup(IConfiguration configuration)
{
配置 = 配置。
}
public IConfiguration 配置 { get; }
//此方法被運行時呼叫。使用此方法來向容器添加服務。
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection"))。
/*services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>(); */
services.AddIdentity<ApplicationUser, IdentityRole>().AddEntityFrameworkStores<ApplicationDbContext>().AddDefaultTokenProviders() 。
services.AddTransient<IEmailSender, EmailSender>()。
services.AddControllersWithViews()。
services.AddRazorPages().AddMvcOptions(options => options.Filters.Add(new AuthorizeFilter())。
services.AddSingleton<IConfiguration>(Configuration)。
services.AddMvc(options => options.EnableEndpointRouting = false)。
services.AddMvc().AddRazorRuntimeCompilation()。
}
//此方法會被運行時呼叫。使用此方法來配置HTTP請求管道。
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage()。
app.UseDatabaseErrorPage();
}
else { env.IsDevelopment()
{
app.UseExceptionHandler("/Home/Error")。
//HSTS的默認值是30天。你可能想在生產場景中改變這個值,見https://aka.ms/aspnetcore-hsts。
app.UseHsts()。
}
app.UseHttpsRedirection()。
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages().RequireAuthorization()。
endpoints.MapControllerRoute()
名稱。"身份"。
模式。"{area:existence}/{controller=Home}/{action=Index}/{id?}")。)
endpoints.MapControllerRoute(
名稱。"default"。
模式。"{controller=Home}/{action=Index}/{id?}")。)
endpoints.MapRazorPages()。
});
}
}
如果有任何幫助,我們將非常感激。謝謝你。
uj5u.com熱心網友回復:
在services.ConfigureApplicationCookie中定義登錄路徑,像這樣:
services.ConfigureApplicationCookie(options =>
{
options.LoginPath = new PathString("/Identity/Account/Login") 。
//其他屬性。
});
uj5u.com熱心網友回復:
我剛剛在GitHub上看了一下,發現Account/Login被設定為CookieAuthenticationDefaults中的一個默認值。然后,我發現它被PostConfigureCookieAuthenticationOptions使用,它在沒有指定任何配置選項的情況下設定合理的配置選項。在我看來,你必須這樣配置:
services.ConfigureApplicationCookie(x => x.LoginPath = "/identity/account/login") 。
x在這種情況下是CookieAuthenticationOptions的型別,這就是PostConfigureCookieAuthenticationOptions所要讀取的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/320350.html
標籤:
