2011-11-27 65 views
7

如果cookie中存在UserName和Password,我想在masterpage的page_load中自动登录我的用户!
所以我写了下面的代码:服务器在发送HTTP头之后无法修改cookie,Fix如何?

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

} 

有时我有以下错误:

系统。 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(),真)。

这个错误意味着什么,我该如何防止它?

回答

10

“System.Web.HttpException:服务器之后HTTP标头已被送往不能修改饼干。”

该错误表明您在http响应完成后尝试修改cookie。

我认为问题在于您在执行 FormsAuthentication.SignOut()后试图修改cookie。

按照MSDN,这会发生什么时SignOut()方法被调用

当SignOut方法被调用时,重定向到应用程序的登录页面是由通过调用Redirect方法与endResponse参数集假。直到当前页面执行完成才会发生重定向,因此可以运行其他代码。如果代码不包含明确的重定向到另一个网页,将用户重定向到应用程序的配置文件中配置登录页面。

所以你想重定向发生后修改的cookie。您可以通过在重定向之前设置cookie值来避免此错误。

+0

感谢答案/但你瞧,我的方法没有SignOut或重定向(LoadDataFromCookieIfExistAndLogin()),那么为什么仍然有错误 - >仅ELMAH表明我这个错误和视觉工作室在调试期间显示此错误。在浏览器页面上工作时,此错误不会显示! – MoonLight

+0

我的意思是FormsAuthentication.SignOut();请确保FormsAuthentication.SignOut();修改前不执行/设置cookie值 – testuser

+0

- >没有FormsAuthentication.SignOut();在修改/设置cookie值之前,这正是我想知道为什么我有异常? – MoonLight

3

如果您正在使用ASP.Net标准形式的验证,如果你使用永久性Cookie此功能适用于形式的验证。请参阅MSDN文章here。检查文档的“创建表单身份验证Cookie”部分。

你不需要保持用户名\密码组合是cookie。这不是一个好习惯,因为任何人都可以从cookie中嗅出这个用户名\密码。我强烈建议您阅读上述文章以了解表单验证如何工作。

+0

感谢您的关注。但我的问题是,我在page_load中使用了这些代码。我如何解决我的情况下的错误? – MoonLight

+0

原因可能是因为用户已通过身份验证并且其表单身份验证Cookie已设置。尝试把用户ID在一个新的Cookie – Chandermani

0

快速测试我已经清除了我的浏览器历史记录,并在我的工作很好..

+0

,除非你正在做一些非常奇怪在这种情况下,它会回来事实上这并不会修复异常。 –

相关问题