如何将用户重定向到一个ASP.NET页面未被授权的时候? [英] How to Redirect Users to an ASP.NET page when not Authorized?

查看:165
本文介绍了如何将用户重定向到一个ASP.NET页面未被授权的时候?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要我的用户的情况下重定向到AuthError.aspx页面(您没有访问此页),当他们进行身份验证,但尝试访问的页面,他们无法访问(因为角色对于考试)。如果我设置的web.config这样:

I need my users are redirected to AuthError.aspx page ("You don't have the access to this page") in the case when they are authenticated but try to access the page that they cannot access (because of the role for exam). If I set up web.config so:

<authentication mode="Forms">
  <forms loginUrl="~/Account/Login.aspx" timeout="2880" />
</authentication>

这是系统的错误行为,因为用户已经验证,没有必要给他或她重定向到这个页面。但是如果我写在这里,而不是AuthError.aspx的Login.aspx我怎么会重定向还未验证的用户登录页面?

this is the system's wrong behaviour because an user is already authenticated and there is no need to redirect him or her to this page. But if I write here AuthError.aspx instead Login.aspx how could I redirect not-yet-authenticated user to the login page?

推荐答案

在登录页面的Page_Load中,你要检查,如果用户进行身份验证,如果他们将其重定向到访问拒绝页面:

On the Page_Load of your login page, you'll want to check if the user is authenticated, and if they are to redirect them to your access denied page:

protected void Page_Load(object sender, EventArgs e)
{
    if (User.Identity.IsAuthenticated) // if the user is already logged in
    {
            Response.Redirect("~/AccessDenied.aspx");
    }
}

如果你想获得票友一点,你可以检查RETURNURL参数来确定用户是否来到了页面直接(如通过他们的权利到登录页面保存书签),并处理不同。这里有一个例子:

If you want to get a little fancier, you can check the ReturnUrl parameter to determine if the user came to the page directly (such as through a bookmark they saved right to the login page) and handle that differently. Here's an example:

protected void Page_Load(object sender, EventArgs e)
    {
        if (User.Identity.IsAuthenticated)
        {

            // if they came to the page directly, ReturnUrl will be null.
            if (String.IsNullOrEmpty(Request["ReturnUrl"]))
            {
                 /* in that case, instead of redirecting, I hide the login 
                    controls and instead display a message saying that are 
                    already logged in. */
            }
            else
            {
            Response.Redirect("~/AccessDenied.aspx");
            }
        }
    }

这篇关于如何将用户重定向到一个ASP.NET页面未被授权的时候?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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