asp.net - 未经授权时如何将用户重定向到ASP.NET页?

标签 asp.net authentication authorization

我需要将我的用户重定向到AuthError.aspx页面(“您无权访问此页面”),以进行身份​​验证,但尝试访问他们无法访问的页面(由于考试的角色) 。如果我这样设置web.config:

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

这是系统的错误行为,因为用户已经通过身份验证,因此无需将其重定向到此页面。但是,如果我在此处编写AuthError.aspx而不是Login.aspx,如何将尚未通过身份验证的用户重定向到登录页面?

最佳答案

在登录页面的Page_Load上,您将要检查用户是否已通过身份验证,以及是否要将用户重定向到您的拒绝访问页面:

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

如果您想了解更多,可以检查ReturnUrl参数以确定用户是否直接进入页面(例如,通过他们直接保存在登录页面上的书签)并进行不同的处理。这是一个例子:
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 - 未经授权时如何将用户重定向到ASP.NET页?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4834387/

相关文章:

ios - 使用 asana 的 oauth 授权(重定向 url)

php - Laravel 在主帐户上为所有员工提供服务

javascript - firebase 安全 api 中的 parent() 方法

c# - 带有 Angular Postback 的 ASP.NET WebForms

authentication - HTTPS中的Bitbucket : git push outputs an fatal: Authentication failed

c# - Azure Web App - 多个应用程序托管 - 访问 Web API 但显示来自 Web App 的 web.config 的错误

android - 当我输入相同的用户名时它给了我 "Wrong input"?

python - 如何使用Python和托管身份/SAS凭据从VM访问Azure存储帐户

javascript - 如何在发布前设置TextBox的文本值?

c# - Redis session 状态提供程序 - 设置操作区分大小写?