ASP MVC 5登录用户仍然可以访问登录页面和注册页面吗? [英] ASP MVC 5 Logged in User can still access Login and Registration Pages?

查看:179
本文介绍了ASP MVC 5登录用户仍然可以访问登录页面和注册页面吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ASP MVC 5应用程序,并且我注意到登录的用户仍然可以访问注册和登录页面.我还注意到,当登录用户尝试访问未经授权的控制器操作时,他们将被重定向到登录页面.这令人困惑,因为用户已经登录.

I have an ASP MVC 5 application and I've noticed that logged in user can still access the registration and login pages. I've also noticed that when a logged in user tries to access a controller action to which they are not authorized, they are redirected to the login page. This is confusing because the user is already logged in.

如何解决此问题,以便未经授权的情况下重定向到其他401错误页面或视图.

How do I fix this so that unauthorised redirects to some other 401 error page or view.

推荐答案

在注册/登录页面上,您可以重定向登录的用户:

On registration/login page, you can redirect logged users :

// GET: /Account/Login
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
    if (User.Identity.IsAuthenticated)
    {
        return RedirectToAction("Index", "Account");
    }
    // ...
}

如果使用角色,则可以覆盖AuthorizeAttribute

And if you use role, you can override the AuthorizeAttribute

[AuthorizeRole(Roles="Admin")]
public ActionResult Admin()
{
//...
}

AuthorizeRoleAttribute.cs
覆盖 HandleUnauthorizedRequest

AuthorizeRoleAttribute.cs
Override HandleUnauthorizedRequest

public class AuthorizeRoleAttribute : AuthorizeAttribute
{
    public override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        if (filterContext.HttpContext.User.Identity.IsAuthenticated
            // Check if user is in roles
            && Roles.Split(',').Any(filterContext.HttpContext.User.IsInRole))
        {
            // Not in any role change view
            filterContext.Result = new ViewResult
            {
                ViewName = "~/Views/Shared/UnauthorizedRole.cshtml"
            };
        }
        else{
            base.HandleUnauthorizedRequest(filterContext);
        }
    }
}

这篇关于ASP MVC 5登录用户仍然可以访问登录页面和注册页面吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆