每个用户在第一次登录时总是不能转到相应的页面,重新登录一次之后就正常了。
这是为什么?有人遇到过吗?
public static void GetUserRoles(){
const string rolesCookie = "CSTrasportRoles"; HttpContext Context = HttpContext.Current;
string[] userRoles = null;
string formattedUserRoles; // Is the request authenticated?
if (!Context.Request.IsAuthenticated)
return; // Get the roles this user is in
if ((Context.Request.Cookies[rolesCookie] == null) || (Context.Request.Cookies[rolesCookie].Value == "")) {
formattedUserRoles = String.Join(";", Users.GetUserRolesByName(Context.User.Identity.Name)); // Create authentication ticket
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1, // version
Context.User.Identity.Name, // user name
DateTime.Now, // issue time
DateTime.Now.AddHours(3), // expires every 3 hours
false, // don't persist cookie
formattedUserRoles, // roles
"/"
); // Encrypt the ticket
String cookieStr = FormsAuthentication.Encrypt(ticket); //HttpCookie authenticationCookie = new HttpCookie(FormsAuthentication.FormsCookieName,cookieStr);
// Send the cookie to the client
Context.Response.Cookies[rolesCookie].Value = cookieStr;
Context.Response.Cookies[rolesCookie].Path = "/";
Context.Response.Cookies[rolesCookie].Expires = DateTime.Now.AddMinutes(5);
} else { // Get roles from roles cookie
//
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(Context.Request.Cookies[rolesCookie].Value); if (ticket.Name != Context.User.Identity.Name) { Context.Response.Cookies[rolesCookie].Expires = DateTime.Now; return; } else { //convert the string representation of the role data into a string array
ArrayList rolesArrayList = new ArrayList();
foreach (String role in ticket.UserData.Split( new char[] {';'} )) {
if (role.Length > 0)
rolesArrayList.Add(role);
} userRoles = (string[]) rolesArrayList.ToArray(typeof(string));
} } Context.User = new GenericPrincipal(Context.User.Identity, userRoles);}
这是为什么?有人遇到过吗?
public static void GetUserRoles(){
const string rolesCookie = "CSTrasportRoles"; HttpContext Context = HttpContext.Current;
string[] userRoles = null;
string formattedUserRoles; // Is the request authenticated?
if (!Context.Request.IsAuthenticated)
return; // Get the roles this user is in
if ((Context.Request.Cookies[rolesCookie] == null) || (Context.Request.Cookies[rolesCookie].Value == "")) {
formattedUserRoles = String.Join(";", Users.GetUserRolesByName(Context.User.Identity.Name)); // Create authentication ticket
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1, // version
Context.User.Identity.Name, // user name
DateTime.Now, // issue time
DateTime.Now.AddHours(3), // expires every 3 hours
false, // don't persist cookie
formattedUserRoles, // roles
"/"
); // Encrypt the ticket
String cookieStr = FormsAuthentication.Encrypt(ticket); //HttpCookie authenticationCookie = new HttpCookie(FormsAuthentication.FormsCookieName,cookieStr);
// Send the cookie to the client
Context.Response.Cookies[rolesCookie].Value = cookieStr;
Context.Response.Cookies[rolesCookie].Path = "/";
Context.Response.Cookies[rolesCookie].Expires = DateTime.Now.AddMinutes(5);
} else { // Get roles from roles cookie
//
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(Context.Request.Cookies[rolesCookie].Value); if (ticket.Name != Context.User.Identity.Name) { Context.Response.Cookies[rolesCookie].Expires = DateTime.Now; return; } else { //convert the string representation of the role data into a string array
ArrayList rolesArrayList = new ArrayList();
foreach (String role in ticket.UserData.Split( new char[] {';'} )) {
if (role.Length > 0)
rolesArrayList.Add(role);
} userRoles = (string[]) rolesArrayList.ToArray(typeof(string));
} } Context.User = new GenericPrincipal(Context.User.Identity, userRoles);}
FormsAuthentication.SetAuthCookie(CurrentUser.Nickname,autoLogin.Checked);
这一句,应该说明是通过验证了的,就是重定向出错了,重定向的地址每次都正确,
为什么要第二次重定向才能生效呢?
这是我重定向的方法
redirectUrl = Page.Request.QueryString["ReturnUrl"]; //通过redirectUrl来判断登录后跳转到哪个页面。ReturnUrl的值在转到登录页面之前的页面设定
if (redirectUrl != null) {
Page.Response.Redirect(redirectUrl);
Page.Response.End();
}else{
Page.Response.Redirect(Globals.UrlHome);
Page.Response.End();
Role-based Security with Forms Authentication
http://www.codeproject.com/aspnet/formsroleauth.asp
string redirectUrl = null;
User CurrentUser = new User();
CurrentUser = Users.GetUserInfo(username.Text);
if ((CurrentUser.Password == password.Text)){
FormsAuthentication.SetAuthCookie(CurrentUser.Nickname,autoLogin.Checked);
redirectUrl = Page.Request.QueryString["ReturnUrl"]; //通过redirectUrl来判断登录后跳转到哪个页面。ReturnUrl的值在转到登录页面之前的页面设定
if (redirectUrl != null) {
Page.Response.Redirect(redirectUrl);
Page.Response.End();
}else{
Page.Response.Redirect(Globals.UrlHome);
Page.Response.End();
}
}
我一般使用Javascript来处理
如:
Page.Response.Redirect(redirectUrl);
换为:
Response.write("<Script>self.location.href='" + redirectUrl + "';</Script>");
先是一登陆用户控件
<%@ Control Language="c#" AutoEventWireup="false" Codebehind="SignIn.ascx.cs" Inherits="ICSharp.Web.Modules.SignIn" TargetSchema="http://schemas.microsoft.com/intellisense/ie5" %>
<TABLE id="Table1" cellSpacing="1" cellPadding="1" width="100%" align="center" border="1">
<TR>
<TD><FONT face="宋体">用户</FONT>
<asp:textbox id="TextBoxUserID" runat="server" Width="144px"></asp:textbox><asp:regularexpressionvalidator id="RegularExpressionValidator1" runat="server" ErrorMessage="请输入邮件地址" ControlToValidate="TextBoxUserID"
ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:regularexpressionvalidator>
<asp:RequiredFieldValidator id="RequiredFieldValidator2" runat="server" ErrorMessage="请输入邮件地址" ControlToValidate="TextBoxUserID"></asp:RequiredFieldValidator></TD>
</TR>
<TR>
<TD><FONT face="宋体">密码</FONT>
<asp:textbox id="TextBoxPassword" runat="server" TextMode="Password"></asp:textbox><asp:requiredfieldvalidator id="RequiredFieldValidator1" runat="server" ErrorMessage="密码不能为空" ControlToValidate="TextBoxPassword"></asp:requiredfieldvalidator></TD>
</TR>
<TR>
<TD><asp:button id="ButtonSignIn" runat="server" Text="登录"></asp:button><asp:checkbox id="CheckBoxRemember" runat="server"></asp:checkbox></TD>
</TR>
<TR>
<TD><asp:literal id="LiteralMessage" runat="server"></asp:literal></TD>
</TR>
<TR>
<TD></TD>
</TR>
</TABLE>
//后台登陆按钮
private void ButtonSignIn_Click(object sender, System.EventArgs e)
{
//验证用户,返回的是用户名称
string password = PortalSecurity.Encrypt(TextBoxPassword.Text.Trim());
String userName = PortalSecurity.CheckUserLogin(TextBoxUserID.Text.Trim(),password);
if ( userName != null && userName != "")
{
if(Request.Url.ToString().ToLower().IndexOf("returnurl=") != -1)
FormsAuthentication.RedirectFromLoginPage(userName, CheckBoxRemember.Checked);
else
{
FormsAuthentication.SetAuthCookie(userName, CheckBoxRemember.Checked);
//Response.Redirect(Request.ApplicationPath);
Response.Redirect("Default.aspx");
}
}
else
{
LiteralMessage.Text = "<" + "br" + ">登录失败!" + "<" + "br" + ">";
LiteralMessage.Visible = true;
}
}在HttpApplication中的AuthenticateRequest事件中protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
if (Request.IsAuthenticated == true)
{ String[] roles; if ((Request.Cookies["portalroles"] == null) || (Request.Cookies["portalroles"].Value == ""))
{ roles = AccountSystem.GetRolesByUserName(User.Identity.Name);
String roleStr = String.Join(";",roles); // Create a cookie authentication ticket.
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1, // version
Context.User.Identity.Name, // user name
DateTime.Now, // issue time
DateTime.Now.AddHours(1), // expires every hour
false, // don't persist cookie
roleStr // roles
); // Encrypt the ticket
String cookieStr = FormsAuthentication.Encrypt(ticket); // Send the cookie to the client
Response.Cookies["portalroles"].Value = cookieStr;
Response.Cookies["portalroles"].Path = "/";
Response.Cookies["portalroles"].Expires = DateTime.Now.AddMinutes(1);
}
else
{ // Get roles from roles cookie
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(Context.Request.Cookies["portalroles"].Value);
roles = ticket.UserData.Split( new char[] {';'} );
} // Add our own custom principal to the request containing the roles in the auth ticket
Context.User = new GenericPrincipal(Context.User.Identity, roles);
}
}