我有一個 asp.net core 3.1 MVC 專案。它已添加身份。當我通常單擊按鈕進入登錄頁面或注冊頁面時,它按預期作業。但是,當我在Startup.cs檔案中的控制器或全域授權過濾器上使用[Authorize]時,頁面不會重定向到登錄頁面。
這種情況下的重定向鏈接是
https://localhost:5001/Account/Login?ReturnUrl=/
鏈接應該在哪里
https://localhost:5001/Identity/Account/Login?ReturnUrl=/
如果您仔細觀察,我得到的鏈接中缺少區域名稱“Identity” 。我猜測我的Startup.cs檔案配置有問題,但無法弄清楚是什么。我的專案中有多個區域以及身份
啟動.cs
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
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();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
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();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages().RequireAuthorization();
endpoints.MapControllerRoute(
name: "Identity",
pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
}
}
任何幫助將不勝感激。謝謝。
uj5u.com熱心網友回復:
像這樣定義登錄路徑services.ConfigureApplicationCookie:
services.ConfigureApplicationCookie(options =>
{
options.LoginPath = new PathString("/Identity/Account/Login");
//other properties
});
uj5u.com熱心網友回復:
我剛剛在 GitHub 上瀏覽了一下,發現在CookieAuthenticationDefaultsAccount/Login中被設定為默認值。然后我發現PostConfigureCookieAuthenticationOptions正在使用它,它會在未指定任何配置選項時設定合理的配置選項。從那開始,在我看來你必須像這樣配置它:
services.ConfigureApplicationCookie(x => x.LoginPath = "/identity/account/login");
x在這種情況下是 type CookieAuthenticationOptions,這是PostConfigureCookieAuthenticationOptions正在讀取的內容。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/415902.html
標籤:
