c# - 重定向未经授权的用户 asp net

标签 c# asp.net authentication web active-directory

我正在使用 asp.net 开发一个简单的网站。 我想限制对一侧的访问,以便只允许特定 AD 组中的用户。我已经做到了,而且工作正常。但是,当不在 AD 组中的用户尝试访问该站点时,他们会收到登录提示。如何将未经授权的用户重定向到自定义页面,而不是让他们收到登录提示?

下面是我的 web.config。代码的最低部分是我尝试过但没有成功的部分。

<configuration>
<system.web>
  <compilation debug="true" targetFramework="4.0" />
  <authentication mode="Windows"/>
  <authorization>
    <allow roles="DOMAIN\GROUP"/>
    <deny users="*"/>
  </authorization>
</system.web>

<location path="AccessDenied.aspx">
<system.web>
<authorization>
  <allow users="*"/>
</authorization>
</system.web>
</location>
</configuration>

我已将此添加到 Global.asax.cs:

protected void Application_EndRequest(Object sender, EventArgs e)
    {
        if (HttpContext.Current.Response.Status.StartsWith("401"))
            {
                HttpContext.Current.Response.ClearContent();
                Server.Execute("AccessDenied.aspx");
            }
}

有什么想法吗?

编辑: 我尝试了一些已发布的解决方案,但它们没有用。 但我用这段代码让它工作:

void Application_EndRequest(object sender, System.EventArgs e)
    {
        if (((Response.StatusCode == 401)
        && (Request.IsAuthenticated == true)))
        {
            Response.ClearContent();
            Response.Redirect("~/AccessDenied.aspx");
        }
    }
}

最佳答案

您可以使用 Response.RedirectServer.Transfer

Response.Redirect("AccessDenied.aspx");

完整示例:

protected void Application_EndRequest(Object sender, EventArgs e)
{
  if (HttpContext.Current.Response.Status.StartsWith("401"))
  {
      HttpContext.Current.Response.ClearContent();
      Response.Redirect("AccessDenied.aspx");
  }
}

关于c# - 重定向未经授权的用户 asp net,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18652934/

相关文章:

c# - 分离 POCO 类后尝试从数据库更新 EDMX 时出现 COMException

asp.net - 使用表单例份验证注销从不同浏览器/计算机登录的用户

c# - ASP.NET Core MVC Google Auth 注销问题

authentication - Nginx 基本身份验证不起作用

php - Codeigniter - session 数据未通过数组保存在数据库中

c# - GeoCoding Maps API 是否仅对网站有效?

c# - 基于多列的数据表去除重复行

javascript - JQuery ajax 从 C# 函数返回列表

asp.net - 第一次无法在更新面板内自动将文件上传到服务器

asp.net - 一键式网络发布时是否可以保留文件夹权限?