2011-11-27 19 views
7

UserNameとPasswordがクッキーに存在する場合、masterpageのpage_loadでユーザーに自動ログインしたい!HTTPヘッダーが送信された後、サーバーはCookieを変更できません。

システム:時々、私は以下のエラーを持っている

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

} 

:私は下RoleProviderなどを用いています、私のログインコードを理解するためにも

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


ので、私は以下のコードを書きました。 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)。

このエラーは何を意味し、どうすれば防止できますか?

答えて

10

"System.Web.HttpException:HTTPヘッダーが送信された後、サーバーはCookieを変更できません。"

このエラーは、http応答の完了後にCookieを変更しようとしていることを示しています。

FormsAuthentication.SignOut()を実行した後にCookieを変更しようとしていると思います。 MSDNあたりとして

、このサインアウトメソッドが呼び出されるとサインアウト()メソッドが

呼び出されたときに何が起こるか、アプリケーションのログインページにリダイレクトがendResponseパラメータセットでRedirectメソッドを呼び出すことによって行われます偽にする。リダイレクトは、現在のページの実行が終了するまで行われないため、追加のコードを実行できます。コードに別のページへの明示的なリダイレクトが含まれていない場合、ユーザーはアプリケーションの構成ファイルで構成されたログインページにリダイレクトされます。

リダイレクトが発生した後にCookieを変更しようとしています。このエラーは、リダイレクトの前にCookieの値を設定することで回避できます。

+0

回答がありがたいですが、私のメソッド(LogDataFromCookieIfExistAndLogin())にSignOutまたはRedirectionがありませんので、なぜそのエラーが残っているのか - > elmahが私にこのエラーとビジュアルを表示しますスタジオはこのエラーをデバッグ中に表示します。このエラーはブラウザのページで作業中に表示されません! – MoonLight

+0

私はFormsAuthentication.SignOut()を意味します。 FormsAuthentication.SignOut();を必ず確認してください。 Cookie値を変更/設定する前に実行されません。 – testuser

+0

- > FormsAuthentication.SignOut()はありません。修正する前に/クッキーの値を設定し、これはまさに私は例外がある理由を知りたいのですか? – MoonLight

3

ASP.Net標準フォーム認証を使用している場合、この機能は永続的なCookieを使用する場合はフォーム認証に使用できます。 MSDNの記事hereを参照してください。ドキュメントの「フォーム認証Cookieの作成」セクションを確認してください。

username \ passwordを保存する必要はありません。cookieはCookieです。誰でもこのユーザー名\パスワードをCookieから盗聴できるので、良い方法ではありません。フォーム認証の仕組みを理解するには、上記の記事をお読みください。

+0

ありがとうございます。しかし、私の問題は、私はpage_loadでそれらのコードを使用しています。私のシナリオでそのエラーを修正するにはどうすればいいですか? – MoonLight

+0

ユーザーが認証され、そのフォーム認証Cookieが既に設定されている可能性があります。ユーザーIDを新しいクッキーに入れようとする – Chandermani

0

クイックテストのために私は私のブラウザの履歴をクリアし、私の最後にうまく動作します..

+0

あなたが本当に変な何かをしていない限り、これは実際にその例外を修正することはありません。 –

関連する問題