2011-11-27 17 views
7

voglio accedere automaticamente ai miei utenti a page_load di masterpage se UserName e Password sono presenti nei cookie!
Così ho scritto il codice qui sotto:Il server non può modificare i cookie dopo che le intestazioni HTTP sono state inviate, come 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); 
         } 
        } 
       } 
      } 
     } 
    } 
} 

anche per comprendere i miei codici di accesso sto usando RoleProvider come di seguito:

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

} 

A volte ho l'errore di seguito:

sistema. Web.HttpException: il server non può modificare i cookie dopo che le intestazioni HTTP sono state inviate.

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) 

sembra che il problema è per la linea di seguito:

FormsAuthentication.SetAuthCookie; (drUsers [ "ID"] ToString(), è vero.)

cosa significa questo errore e come posso prevenirlo?

risposta

10

"System.Web.HttpException: il server non può modificare i cookie dopo che le intestazioni HTTP sono state inviate."

Questo errore indica che si sta tentando di modificare i cookie una volta completata la risposta http.

Credo che il problema è che si tenta di modificare i biscotti dopo l'esecuzione FormsAuthentication.SignOut().

Secondo MSDN, questo ciò che accade quando il metodo SignOut() viene chiamato

Quando il metodo SignOut viene chiamato, un reindirizzamento alla pagina di login dell'applicazione è fatta chiamando il metodo Redirect con il set di parametri endResponse a falso. Il reindirizzamento non ha luogo fino a quando la pagina corrente non ha completato l'esecuzione, quindi è possibile eseguire codice aggiuntivo. Se il codice non contiene un reindirizzamento esplicito a un'altra pagina, l'utente viene reindirizzato alla pagina di accesso configurata nel file di configurazione dell'applicazione.

Quindi si sta tentando di modificare i cookie dopo il reindirizzamento. È possibile evitare questo errore impostando il valore del cookie prima del reindirizzamento.

+0

grazie per la risposta/ma come vedi non vi è alcun SignOut o Reindirizzamento nel mio metodo (LoadDataFromCookieIfExistAndLogin()). Quindi perché avere ancora quell'errore -> solo elmah mi mostra questo errore e studio mostra questo errore durante il debug.questo errore non appare quando si lavora sulla pagina nel browser! – MoonLight

+0

Intendo FormsAuthentication.SignOut(); assicurati che FormsAuthentication.SignOut(); non viene eseguito prima di modificare/impostare il valore del cookie – testuser

+0

-> non esiste FormsAuthentication.SignOut(); prima di modificare/impostare il valore del cookie e questo è esattamente quello che voglio sapere perché ho un'eccezione? – MoonLight

3

Se si utilizza l'autenticazione modulo standard ASP.Net, questa funzione è disponibile per l'autenticazione Modulo se si utilizzano cookie permanenti. Vedere l'articolo MSDN here. Seleziona la sezione "Creazione del cookie di autenticazione dei moduli" del documento.

Non è necessario mantenere nome utente \ la combinazione di password è cookie. Non è una buona pratica dato che chiunque può annusare questo nome utente \ password dal cookie. Consiglio vivamente di leggere l'articolo precedente per capire come funziona l'autenticazione Form.

+0

grazie per l'attenzione. ma il mio problema è che ho usato quei codici nel page_load. come posso risolvere questo errore per il mio scenario? – MoonLight

+0

Il motivo forse perché l'utente è autenticato e il suo cookie di Autenticazione Form è già impostato. Prova a inserire l'ID utente in un nuovo cookie – Chandermani

0

per test rapidi Ho cancellato la cronologia del browser e funziona perfettamente sul mio fine ..

+0

Questo non risolverà in realtà quell'eccezione a meno che tu non stia facendo qualcosa di veramente strano, nel qual caso tornerà. –

Problemi correlati