在ASP.NET Core和Identity中,不建议使用URL重定向与ForbidResult或Pass Data to Acccount AccessDenied View。相反,推荐使用标准的身份验证和授权机制。
下面是一个示例解决方法,演示如何在ASP.NET Core和Identity中处理访问被拒绝的情况:
public void ConfigureServices(IServiceCollection services)
{
// 添加身份验证服务
services.AddAuthentication(options =>
{
options.DefaultScheme = IdentityConstants.ApplicationScheme;
options.DefaultSignInScheme = IdentityConstants.ExternalScheme;
})
.AddIdentityCookies(options => { });
// 添加授权服务
services.AddAuthorization();
// 其他服务配置...
}
[Authorize]
public class MyController : Controller
{
// 需要授权的操作
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// 其他中间件配置...
// 处理访问被拒绝的情况
app.Use(async (context, next) =>
{
await next();
if (context.Response.StatusCode == 403)
{
// 访问被拒绝,重定向到自定义的拒绝访问页面
context.Response.Redirect("/Account/AccessDenied");
}
});
// 其他中间件配置...
}
public class AccountController : Controller
{
// 其他操作...
[HttpGet]
public IActionResult AccessDenied()
{
return View();
}
}
通过以上解决方法,当用户访问需要授权的操作但未通过身份验证或未授权时,会被重定向到自定义的拒绝访问页面。