2011-11-27 27 views
7

Quiero iniciar sesión automáticamente mis usuarios en page_load de la página maestra si UserName y Password existen en las cookies.
así que escribió el código abajo:El servidor no puede modificar las cookies después de que se hayan enviado encabezados HTTP, ¿cómo se corrigió?

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

también para la comprensión de mi nombre y contraseña estoy usando RoleProvider, como a continuación:

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 veces tengo el error abajo:

sistema. Web.HttpException: el servidor no puede modificar las cookies después de que se hayan enviado encabezados HTTP.

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) 

Parece que el problema es para la línea de abajo:

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

¿Qué significa este error y cómo puedo evitarlo?

Respuesta

10

"System.Web.HttpException: el servidor no puede modificar las cookies después de que se hayan enviado los encabezados HTTP".

Ese error indica que está intentando modificar las cookies después de que se complete la respuesta http.

Creo que el problema es que tratando de modificar las galletas después de la ejecución de FormsAuthentication.SignOut().

Según MSDN, esto lo que sucede cuando el método SignOut() se llama

Cuando se llama al método SignOut, una redirección a la página de inicio de sesión de la aplicación se hace llamando al método de redireccionamiento con el conjunto de parámetros endResponse a falso La redirección no tiene lugar hasta que la página actual haya terminado de ejecutarse, por lo que se puede ejecutar código adicional. Si el código no contiene un redireccionamiento explícito a otra página, el usuario se redirige a la página de inicio de sesión configurada en el archivo de configuración de la aplicación.

Así que está tratando de modificar las cookies después de que ocurre la redirección. Puede evitar este error configurando el valor de la cookie antes de la redirección.

+0

gracias por la respuesta/pero como ve no hay SignOut o redirección en mi método (LoadDataFromCookieIfExistAndLogin()). ¿Por qué todavía tiene ese error -> solo elmah me muestra este error y visual studio muestra este error durante la depuración. ¡Este error no aparece cuando se trabaja en la página en el navegador! – MoonLight

+0

Me refiero a FormsAuthentication.SignOut(); por favor, asegúrese de que FormsAuthentication.SignOut(); no se ejecuta antes de modificar/establecer el valor de cookie – testuser

+0

-> no hay FormsAuthentication.SignOut(); antes de modificar/configurar el valor de la cookie y esto es exactamente lo que quiero saber ¿por qué tengo una excepción? – MoonLight

3

Si está utilizando la autenticación de formulario estándar ASP.Net, esta característica está disponible para la autenticación de Formulario si utiliza cookies persistentes. Consulte el artículo here de MSDN. Compruebe la sección 'Crear la cookie de autenticación de formularios' del documento.

No es necesario que la combinación nombre usuario \ contraseña sea cookie. No es una buena práctica ya que cualquier persona puede oler este nombre de usuario/contraseña de la cookie. Recomiendo encarecidamente que lea el artículo anterior para comprender cómo funciona la autenticación de formularios.

+0

gracias por la atención. pero mi problema es que utilicé esos códigos en page_load. ¿Cómo puedo arreglar ese error para mi escenario? – MoonLight

+0

El motivo puede deberse a que el usuario está autenticado y su cookie de autenticación de formulario ya está configurada. Trate de poner la identificación de usuario en una nueva cookie – Chandermani

0

para pruebas rápidas He borrado el historial de mi navegador y funciona bien en mi extremo ..

+0

Esto no solucionará esa excepción a menos que estés haciendo algo realmente extraño, en cuyo caso volverá. –

Cuestiones relacionadas