c# - Asp Net Core授权

标签 c# asp.net-core-1.0

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

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

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/

相关文章:

c# - 用一个字符替换字符串中的整个字符

.net-core - 找不到可执行文件匹配命令 "dotnet-add"

asp.net - .NET Core是否稳定才能启动真正的产品?

c# - 为具有大量依赖项的库创建包装器的正确方法

c# - NVarChar 到 C# 数据类型

javascript - 如何在页面加载时弹出对话框

asp.net-core - 完全兼容 ASP.NET Core 的 Glimpse 诊断平台

c# - 在 ASP.NET Core MVC 模型中访问 _context

asp.net-mvc - 多个复选框表单的 ASP.Net MVC6 语法

c# - C# 中的端口映射不起作用