gpt4 book ai didi

c# - Asp Net Core授权

转载 作者:太空宇宙 更新时间:2023-11-03 15:00:50 25 4
gpt4 key购买 nike

问题:每当普通用户尝试访问只能由管理员访问的页面时,用户总是被重定向到登录而不是访问被拒绝的页面。

问题:普通用户在访问受限页面时,如何看到拒绝访问页面?

Controller :

[Authorize(Roles = "Administrator")]
public class AdminOnlyController: Controller{

}

Startup.cs

app.UseIdentity();

app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AuthenticationScheme = "FirstCookieAuthentication",
AutomaticAuthenticate = true,
AutomaticChallenge = true,
AccessDeniedPath = new PathString("/Forbidden/"),
LoginPath = new PathString("/Conotroller/Login"),
});

最佳答案

拒绝访问只是一个状态代码,如未找到、内部错误等。要管理状态代码,您可以使用中间件“app.UseStatusCodePages”。

代码:

if (env.IsDevelopment())
{
// see something more here
}
else
{
app.UseStatusCodePagesWithReExecute("/StatusCode/{0}");
}

然后在 StatusCodeController 中,构建一个与您提供的路由相匹配的操作结果,例如:

    [HttpGet("/StatusCode/{statusCode}")]
public IActionResult Index(int statusCode)
{
string statusmessage = "";
switch (statusCode)
{
case 400:
statusmessage = "Bad request: The request cannot be fulfilled due to bad syntax";
break;
case 403:
statusmessage = "Forbidden";
break;
//all codes here...
default:
statusmessage = "That’s odd... Something we didn't expect happened";
break;
}

// return appropriate view
// or same view with different message, eg from ViewBag
}

关于c# - Asp Net Core授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46233587/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com