How to Redirect Users to an ASP.NET page when not Authorized?

前端 未结 6 870
小蘑菇
小蘑菇 2020-12-28 15:33

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 t

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-28 16:09

    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");
        }
    }
    

    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");
                }
            }
        }
    

提交回复
热议问题