重定向至使用.NET Core 6中的[授权]属性的自定义登录页



我正在使用.net 6进行应用程序开发。I、 我正在使用来自.net core的Identity Manager。我制作了一个自定义的引导程序登录页面。此外,根据我的应用程序结构,我不需要_loginpartial.chtml.

我已经在MVC.net核心项目的HomeController中为默认的Privacy页面操作赋予了[授权]属性。还将锚标签添加到了主页中的隐私>索引.cshtml.

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

但是,如果我从上面的链接中删除/Identity/,那么页面就会加载。iehttps://localhost:7188/Account/Login?ReturnUrl=%2FHome%2FPrivacy.

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

当我添加应用程序时。MapRazorPages((;在端点部分之后,链接工作!但它提供了一个与我创建的完全不同的登录页面。它似乎正在加载一个预构建的Identity页面。如何使用我的登录页面?当我使用[授权]属性来保护我的控制器方法时?

程序.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://learn.microsoft.com/en-us/aspnet/core/security/authentication/identity-configuration?view=aspnetcore-6.0

解决方案是将我的自定义登录页面映射到Identity。这是通过在.net 6 的程序.cs中添加以下代码行实现的

services.ConfigureApplicationCookie(options =>
{
//Location for your Custom Access Denied Page
options.AccessDeniedPath = "Account/AccessDenied";
//Location for your Custom Login Page
options.LoginPath = "Account/Login";
});

在我的案例中,它正在寻找"MicrosoftIdentity/Account/AccessDenied";。我通过在控制器中添加以下方法解决了这个问题。

[HttpGet]
[Route("/MicrosoftIdentity/Account/AccessDenied")]
public ActionResult AccessDenied()
{
return View();
}

最新更新