c# - 在 ASP.NET 中按角色重定向登录
问题描述
我为我的 ASP.NET 站点创建了 2 个角色,即管理员和成员。在登录时,我想根据他们的角色将他们重定向到页面。如果用户是管理员,它将被重定向到管理区域,如果是成员,则重定向到成员区域。我已经能够让它为管理员工作,但对于成员来说,它只是刷新页面,甚至登录状态也不会改变。
<%@ Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true" CodeBehind="Login.aspx.cs" Inherits="Assignment7run.WebForm5" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
<style type="text/css">
.auto-style2 {
width: 508px;
}
</style>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<h1 style="font-family: Georgia" class="auto-style2">Login to jQuery Society</h1>
<asp:Login ID="Login1" runat="server" OnAuthenticate="Login1_Authenticate" CreateUserText="Sign Up for an account on jQuery Society" CreateUserUrl="~/SignUp.aspx" MembershipProvider="DefaultMembershipProvider">
</asp:Login>
<asp:LoginStatus ID="LoginStatus1" runat="server" />
<br />
</asp:Content>
后面的代码。当我添加 FormsAuthentication.SetAuthCookie(Login1.UserName, true); 时,甚至管理员登录也开始工作。行来发挥作用。当我将其添加到成员时,该页面不运行。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
namespace Assignment7run
{
public partial class WebForm5 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Request.IsAuthenticated && !string.IsNullOrEmpty(Request.QueryString["ReturnUrl"]))
Response.Redirect("~/NoAccess.aspx");
}
}
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
if (Membership.ValidateUser(Login1.UserName, Login1.Password))
{
e.Authenticated = true;
if (Roles.IsUserInRole(Login1.UserName, "Admin"))
{
FormsAuthentication.SetAuthCookie(Login1.UserName, true);
Response.Redirect("~/Admin/adminWelcome.aspx");
}
if (Roles.IsUserInRole(Login1.UserName, "Members"))
{
Response.Redirect("~/Members/MemberPage.aspx");
}
}
}
}
}
解决方案
移动 setAuthCookie 然后在此页面上的 MemberPage.aspx 页面上显示您的代码 cuz 错误。如果没有 setAuthCookie,您总是会在页面 Auth 上返回,但是当您设置它时,您将在新页面上重定向您需要的内容并得到它错误
if (Membership.ValidateUser(Login1.UserName, Login1.Password))
{
e.Authenticated = true;
FormsAuthentication.SetAuthCookie(Login1.UserName, true); //Do It
if (Roles.IsUserInRole(Login1.UserName, "Admin"))
{
Response.Redirect("~/Admin/adminWelcome.aspx");
}
if (Roles.IsUserInRole(Login1.UserName, "Members"))
{
Response.Redirect("~/Members/MemberPage.aspx");
}
}
推荐阅读
- kubernetes - 如何将 Kubernetes 服务类型“LoadBalancer”与特定云负载均衡器集成
- python - 扩展 code.InteractiveInterpreter 与历史,选项卡完成,
- python - Pyro4:在远程子对象上调用方法而不尝试返回子对象
- javascript - 如果我使用两个“if”语句而不仅仅是一个“if/else”语句,为什么二进制搜索算法不起作用?
- textures - 如何正确可视化 A-Frame 中的 AO 地图贡献
- python - 在 C++ 中实现 python np.fromstring()
- google-sheets - 创建 ImportXML 以从任何内容创建者的视频页面获取最后 30 个视频的单个 YouTube 视频视图。可能的?
- rest - WebLogic 12c JAX-RS 和 JSON 编组
- promql - 如何编写 PromQL 单元测试来检查警报是否未触发?
- r - 在 R 中使用 cor.test 函数