2011-11-27 25 views
7

tôi muốn tự động đăng nhập người dùng của mình tại page_load của trang chủ nếu Tên người dùng và Mật khẩu tồn tại trong cookie!
vì vậy tôi đã viết đoạn code dưới đây:Máy chủ không thể sửa đổi cookie sau khi tiêu đề HTTP đã được gửi, cách sửa lỗi?

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

cũng để hiểu mã đăng nhập của tôi tôi đang sử dụng RoleProvider như dưới đây:

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

} 

đôi khi tôi có lỗi dưới đây:

System. Web.HttpException: Máy chủ không thể sửa đổi cookie sau khi tiêu đề HTTP đã được gửi.

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) 

có vẻ như vấn đề là cho các dòng dưới đây:

FormsAuthentication.SetAuthCookie; (drUsers [ "ID"] ToString(), đúng.)

lỗi này có ý nghĩa gì và làm cách nào để ngăn chặn lỗi này?

Trả lời

10

"System.Web.HttpException: Máy chủ không thể sửa đổi cookie sau khi tiêu đề HTTP đã được gửi."

Lỗi đó cho biết rằng bạn đang thử sửa đổi cookie sau khi phản hồi http được hoàn thành.

Tôi nghĩ rằng vấn đề là bạn đang cố sửa đổi cookie sau khi thực hiện FormsAuthentication.SignOut().

Theo MSDN, điều này những gì sẽ xảy ra khi phương pháp SignOut() được gọi

Khi phương pháp SignOut được gọi, chuyển hướng đến trang đăng nhập của ứng dụng được thực hiện bằng cách gọi phương thức Redirect với các thiết lập thông số endResponse thành sai. Chuyển hướng không diễn ra cho đến khi trang hiện tại hoàn thành việc thực thi, vì vậy mã bổ sung có thể được chạy. Nếu mã không chứa chuyển hướng rõ ràng đến trang khác, người dùng sẽ được chuyển hướng đến trang đăng nhập được định cấu hình trong tệp cấu hình của ứng dụng.

Vì vậy, bạn đang cố gắng sửa đổi các cookie sau khi chuyển hướng xảy ra. Bạn có thể tránh lỗi này bằng cách đặt giá trị cookie trước khi chuyển hướng.

+0

cảm ơn cho câu trả lời/nhưng như bạn thấy không có SignOut hoặc Redirection trong phương pháp của tôi (LoadDataFromCookieIfExistAndLogin()) .vì vậy tại sao vẫn có lỗi đó -> chỉ elmah cho tôi thấy lỗi này và hình ảnh studio hiển thị lỗi này trong khi gỡ lỗi.những lỗi này không xuất hiện khi làm việc trên trang trong trình duyệt! – MoonLight

+0

Tôi có nghĩa là FormsAuthentication.SignOut(); hãy đảm bảo rằng FormsAuthentication.SignOut(); không thực thi trước khi bạn sửa đổi/đặt giá trị cookie – testuser

+0

-> không có FormsAuthentication.SignOut(); trước khi sửa đổi/thiết lập giá trị cookie và điều này là chính xác những gì tôi muốn biết lý do tại sao tôi có ngoại lệ? – MoonLight

3

Nếu bạn đang sử dụng xác thực mẫu chuẩn ASP.Net, tính năng này có sẵn để xác thực biểu mẫu nếu bạn sử dụng cookie liên tục. Xem bài viết MSDN here. Kiểm tra phần 'Tạo Cookie Xác thực Biểu mẫu' của tài liệu.

Bạn không cần phải giữ kết hợp tên người dùng \ mật khẩu là cookie. Nó không phải là một thực hành tốt như bất cứ ai có thể sniff tên người dùng này \ mật khẩu từ cookie. Tôi khuyên bạn nên đọc bài viết trên để hiểu cách thức hoạt động của xác thực Mẫu.

+0

cảm ơn sự quan tâm. nhưng vấn đề của tôi là, tôi đã sử dụng các mã đó trong page_load. làm thế nào tôi có thể sửa lỗi đó cho kịch bản của tôi? – MoonLight

+0

Lý do có thể do người dùng được xác thực và cookie Xác thực biểu mẫu đã được đặt. Hãy thử để đặt User ID trong một cookie mới – Chandermani

0

để kiểm tra nhanh Tôi đã xóa lịch sử trình duyệt của mình và hoạt động tốt ở phần cuối của mình ..

+0

Điều này sẽ không thực sự khắc phục ngoại lệ đó trừ khi bạn đang làm một cái gì đó thực sự kỳ lạ trong trường hợp nó sẽ trở lại. –

Các vấn đề liên quan