使用 .NET Core 6 中的 [Authorize] 属性重定向到自定义登录页面

Redirect to custom login page using [Authorize] attribute in .NET Core 6

我正在使用 .net 6 进行应用程序开发。我正在使用 .net 核心的 Identity Manager。我制作了一个自定义 bootstrap 登录页面。另外,根据我的应用程序结构,我不需要 _loginpartial.cshtml.

我已将 [Authorize] 属性赋予 MVC .net 核心项目中 HomeController 中的默认隐私页面操作。还在主页>Index.cshtml.

中添加了隐私锚标签

当我点击 link 时,应用程序弹出 404 页面未找到错误。 它正在重定向到以下 link:https://localhost:7188/Identity/Account/Login?ReturnUrl=%2FHome%2FPrivacy 。但页面未加载。

但是,如果我从上面的 link 中删除 /Identity/,则页面会加载。即 https://localhost:7188/Account/Login?ReturnUrl=%2FHome%2FPrivacy.

因为我使用的是 .net 6,所以我将 Startup.cs 中的所有代码都用到了 Program.cs 中,并相应地迁移了代码。

当我添加app.MapRazorPages();在端点部分之后 link 有效!但它提供了一个与我创建的完全不同的登录页面。它似乎正在加载一个预建的身份页面。如何使用我的登录页面?当我使用 [Authorize] 属性来保护我的控制器方法时?

program.cs

using MyApplication.Data;
using MyApplication.Service;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddIdentity<IdentityUser, IdentityRole>().AddEntityFrameworkStores<ApplicationDbContext>().AddDefaultTokenProviders().AddDefaultUI();
builder.Services.AddControllersWithViews(options => { options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute()); });
builder.Services.AddRazorPages();

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();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();


app.MapControllerRoute(name: "default", pattern: "{controller=Home}/{action=Index}/{id?}");
app.MapRazorPages();

app.Run();

如果我需要提供更多详细信息来解决问题,请告诉我?

我在此处的 Microsoft 知识库中找到了上述问题的解决方案:https://docs.microsoft.com/en-us/aspnet/core/security/authentication/identity-configuration?view=aspnetcore-6.0

解决方案是将我的自定义登录页面映射到身份。这是通过在 program.cs for .net 6

中添加以下代码行来实现的
services.ConfigureApplicationCookie(options =>
{
    //Location for your Custom Access Denied Page
    options.AccessDeniedPath = "Account/AccessDenied";

    //Location for your Custom Login Page
    options.LoginPath = "Account/Login";
});