简体   繁体   English

MVC 4 在用户之前未经授权后从登录页面重定向到上一页

[英]MVC 4 redirect from login page to previous page after user weren´t authorized before

i would like to ask if c# or mvc has a easy way to redirect user back to the page they came from if they are try to enter a unauthorized page and have to login?我想问一下,如果 c# 或 mvc 有一种简单的方法可以将用户重定向回他们来自的页面,如果他们试图进入未经授权的页面并且必须登录?

I already have a very huge web app and i´ma litte bit too lazy to overwork every single method with a direction string to it´s page for the case of unauthorization.我已经有一个非常庞大的网络应用程序,我有点懒得用一个指向它的页面的方向字符串的方法来处理未经授权的情况。 So if it is possible i would like to choose another way, more resitent for changes.因此,如果可能的话,我想选择另一种方式,更不愿意改变。

For authorization at moment i use a custom class inherited from AuthorizeAttribute:对于授权,我使用从 AuthorizeAttribute 继承的自定义类:

public class CustomAuthorizationAttribute : AuthorizeAttribute
{
    public RolesEnum[] RequiredRoles;

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (httpContext == null) throw new ArgumentNullException("httpContext");
        if (!httpContext.User.Identity.IsAuthenticated) return false;
        if (RequiredRoles.Contains(AzaraSession.Current.UserComparison.GetRole())) return true;
        else return false;
    }
}

we can save route path in Session before redirecting to Authentication page and immediately after authenticating with help of session we can redirect back,我们可以在重定向到身份验证页面之前在会话中保存路由路径,并且在会话的帮助下进行身份验证后,我们可以立即重定向回来,

this will be one time code changes.这将是一次代码更改。

Thanks and lets us know in case of any issue.谢谢,如果有任何问题,请告诉我们。

I found a very easy solution in the AuthorizeAttribute directly.我直接在 AuthorizeAttribute 中找到了一个非常简单的解决方案。 It creates an parameter 'returnUrl', which have the url of the failed login page.它创建了一个参数“returnUrl”,其中包含失败登录页面的 url。 So i just need to take this parameter in the 'LogOn' method and 'Redirect' to this page after login is operated.所以我只需要在'LogOn'方法中带上这个参数,然后在登录操作后'重定向'到这个页面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM