在 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因为此页面上的错误。 如果没有setAuthCookie,您将始终返回页面身份验证,但是当您设置它时,您将在新页面上重定向您需要的内容并得到错误

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

最新更新