简体   繁体   中英

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?

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:

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. It creates an parameter 'returnUrl', which have the url of the failed login page. So i just need to take this parameter in the 'LogOn' method and 'Redirect' to this page after login is operated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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