如果Cookie中存在UserName和Password,我想在主页的page_load上自动登录我的用户! 所以我写了下面的代码:
protected void Page_Load(object sender, EventArgs e)
{
LoadDataFromCookieIfExistAndLogin();
}
private void LoadDataFromCookieIfExistAndLogin()
{
string Query = Request.Url.Query.ToString();
string[] Ar_Query = new string[2];
string[] splitter = { "%2f" };
Ar_Query = Query.Split(splitter, System.StringSplitOptions.None);
string[] Ar_new_Query = new string[2];
int minLength = Math.Min(Ar_Query.Length, Ar_new_Query.Length);
Array.Copy(Ar_Query, Ar_new_Query, minLength);
if (string.IsNullOrEmpty(Ar_new_Query[1]))
{
Ar_new_Query[1] = string.Empty;
}
if ((Request.QueryString["ReturnURL"] != null) && (Ar_new_Query[1].ToString().ToUpper() == "ADMIN"))
{
Session.Clear();
FormsAuthentication.SignOut();
}
else if ((Request.QueryString["ReturnURL"] != null) && (Ar_new_Query[1].ToString().ToUpper() == "ELMAH.AXD"))
{
Session.Clear();
FormsAuthentication.SignOut();
}
else
{
HttpCookie Situation_Cookie = Request.Cookies["Situation"];
if (Situation_Cookie != null)
{
if (Situation_Cookie["Login"] == "Yes")
{
HttpCookie Data_Cookie = Request.Cookies["Data"];
if (Data_Cookie != null)
{
string UserName = Data_Cookie["UserName"].ToString();
string PassWord = ata_Cookie["PassWord"].ToString();
string HashedPass = FormsAuthentication.HashPasswordForStoringInConfigFile(PassWord, "MD5");
DataSet dsUsers = DataLayer.Users.SelectRowForLogin_FromCookie(UserName, HashedPass);
if (dsUsers.Tables["Users"].Rows.Count > 0)
{
DataRow drUsers = dsUsers.Tables["Users"].Rows[0];
if (Session["User_ID"] == null)
{
Session["UserName"] = UserName;
Session["Password"] = PassWord;
Session["User_ID"] = drUsers["ID"].ToString();
Session["UserType_ID"] = drUsers["UserType_ID"].ToString();
DataLayer.OnlineUsers.UpdateRow_UserID_By_SessionID(
Session["User_ID"],
Session.SessionID);
}
if (!HttpContext.Current.User.Identity.IsAuthenticated)
{
FormsAuthentication.SetAuthCookie(drUsers["ID"].ToString(), true);
}
}
}
}
}
}
}
也是为了理解我的登录代码,我正在使用RoleProvider,如下所示:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Data;
namespace NiceFileExplorer.Classes
{
public class NiceFileExplorerRoleProvider : RoleProvider
{
public override void AddUsersToRoles(string[] usernames, string[] roleNames)
{
throw new NotImplementedException();
}
public override string ApplicationName
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public override void CreateRole(string roleName)
{
throw new NotImplementedException();
}
public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
{
throw new NotImplementedException();
}
public override string[] FindUsersInRole(string roleName, string usernameToMatch)
{
throw new NotImplementedException();
}
public override string[] GetAllRoles()
{
throw new NotImplementedException();
}
//public override string[] GetRolesForUser(string username)
public override string[] GetRolesForUser(string User_ID)
{
string[] UserTypes = new string[1];
DataSet dsUser = DataLayer.Users.SelectRowWithUserTypeInfo(int.Parse(User_ID));
if (dsUser.Tables["Users"].Rows.Count > 0)
{
DataRow drUser = dsUser.Tables["Users"].Rows[0];
UserTypes[0] = drUser["Name"].ToString();
}
if (User_ID == "-255")
{
UserTypes[0] = "Administrators";
}
return UserTypes;
}
public override string[] GetUsersInRole(string roleName)
{
throw new NotImplementedException();
}
public override bool IsUserInRole(string username, string roleName)
{
throw new NotImplementedException();
}
public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
{
throw new NotImplementedException();
}
public override bool RoleExists(string roleName)
{
throw new NotImplementedException();
}
}
}
有时我会遇到以下错误:
System.Web.HttpException:服务器无法在发送HTTP标头后修改Cookie。
System.Web.HttpUnhandledException (0x80004005): Exception of type 'System.Web.HttpUnhandledException' was thrown. ---> System.Web.HttpException (0x80004005): Server cannot modify cookies after HTTP headers have been sent.
at System.Web.HttpCookieCollection.Add(HttpCookie cookie)
at System.Web.Security.FormsAuthentication.SetAuthCookie(String userName, Boolean createPersistentCookie, String strCookiePath)
at NiceFileExplorer.en.Site1.Page_Load(Object sender, EventArgs e)
at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.HandleError(Exception e)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest()
at System.Web.UI.Page.ProcessRequest(HttpContext context)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
似乎问题出在以下几行:
FormsAuthentication.SetAuthCookie(drUsers [“ID”]。ToString(),true);
这个错误意味着什么,我该如何预防呢?
答案 0 :(得分:11)
“System.Web.HttpException:服务器无法在发送HTTP标头后修改cookie。”
该错误表示您在http响应完成后尝试修改cookie。
我认为问题是你试图在执行后修改cookie FormsAuthentication.SignOut()。
根据MSDN,这是在调用SignOut()方法时发生的事情
调用SignOut方法时,通过调用Redirect方法并将endResponse参数设置为false来重定向到应用程序的登录页面。在当前页面执行完毕之前,重定向不会发生,因此可以运行其他代码。如果代码不包含显式重定向到另一个页面,则会将用户重定向到应用程序配置文件中配置的登录页面。
因此,您尝试在重定向发生后修改Cookie。您可以通过在重定向之前设置cookie值来避免此错误。
答案 1 :(得分:3)
如果您使用的是ASP.Net标准表单身份验证,则如果您使用持久性Cookie,则此功能可用于表单身份验证。请参阅MSDN文章here。检查文档的“创建表单身份验证Cookie”部分。
您不需要保留用户名\密码组合是cookie。这不是一个好习惯,因为任何人都可以从cookie中嗅出这个用户名\密码。我强烈建议您阅读上述文章,以了解表单身份验证的工作原理。
答案 2 :(得分:0)
快速测试我已经清除了我的浏览器历史记录,并在我的最终工作正常..