2012-07-08 69 views
1

我正在编写代码以便在下次登录控制时为Remember Me存储Cookie。如果用户选中了“记住我”复选框,那么这会将用户的用户名存储在文本框中。而我的登录控制是在LoginView中设置的。未将对象引用设置为对象中的一个实例记住我

当我运行该程序,并在登录控件中的字段填写,并点击提交(有或没有选中复选框),它给了我这个错误:

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object. 

Source Error: 

Line 65: 
Line 66:   HttpCookie myCookie = new HttpCookie("myCookie"); 
Line 67:   if (RememberMe.Checked == true) //here is the line giving error 
Line 68:   { 
Line 69:    myCookie.Values.Add("username", Login1.UserName); 

Line: 67 

这是登录的代码控制:

<asp:LoginView ID="LoginView1" runat="server"> 
     <AnonymousTemplate> 
     <asp:Login ID="Login1" runat="server" onloggingin="Login1_LoggingIn" 
       onloginerror="Login1_LoginError" onauthenticate="Login1_Authenticate" 
       RememberMeSet="True"> 
      <LayoutTemplate> 
       <table cellpadding="1" cellspacing="0" style="border-collapse:collapse;"> 
        <tr> 
         <td> 
          <table cellpadding="0"> 
           <tr> 
            <td align="center" colspan="2"> 
             Log In</td> 
           </tr> 
           <tr> 
            <td align="right"> 
             <asp:Label ID="UserNameLabel" runat="server" AssociatedControlID="UserName">User Name:</asp:Label> 
            </td> 
            <td> 
             <asp:TextBox ID="UserName" runat="server"></asp:TextBox> 
             <asp:RequiredFieldValidator ID="UserNameRequired" runat="server" 
              ControlToValidate="UserName" ErrorMessage="User Name is required." 
              ToolTip="User Name is required." ValidationGroup="ctl00$Login1">*</asp:RequiredFieldValidator> 
            </td> 
           </tr> 
           <tr> 
            <td align="right"> 
             <asp:Label ID="PasswordLabel" runat="server" AssociatedControlID="Password">Password:</asp:Label> 
            </td> 
            <td> 
             <asp:TextBox ID="Password" runat="server" TextMode="Password"></asp:TextBox> 
             <asp:RequiredFieldValidator ID="PasswordRequired" runat="server" 
              ControlToValidate="Password" ErrorMessage="Password is required." 
              ToolTip="Password is required." ValidationGroup="ctl00$Login1">*</asp:RequiredFieldValidator> 
            </td> 
           </tr> 
           <tr> 
            <td colspan="2"> 
             <asp:CheckBox ID="RememberMe" runat="server" 
              Text="Remember me next time." /> 
            </td> 
           </tr> 
           <tr> 
            <td align="center" colspan="2" style="color:Red;"> 
             <asp:Literal ID="FailureText" runat="server" EnableViewState="False"></asp:Literal> 
            </td> 
           </tr> 
           <tr> 
            <td align="right" colspan="2"> 
             <asp:Button ID="LoginButton" runat="server" CommandName="Login" Text="Log In" 
              ValidationGroup="ctl00$Login1" /> 
            </td> 
           </tr> 
          </table> 
         </td> 
        </tr> 
       </table> 
      </LayoutTemplate> 
     </asp:Login> 
     </AnonymousTemplate> 

     <LoggedInTemplate> 
      <asp:LoginStatus ID="LoginStatus1" runat="server" /> 

     </LoggedInTemplate> 
     </asp:LoginView> 

这是在后面的代码:

protected void Page_Load(object sender, EventArgs e) 
{ 
    System.Web.UI.WebControls.Login Login1 = (System.Web.UI.WebControls.Login)LoginView1.FindControl("Login1"); 
    TextBox UserName = (TextBox)Login1.FindControl("UserName"); 


    if (Request.Cookies["myCookie"] != null) 
    { 

     HttpCookie cookie = Request.Cookies.Get("myCookie"); 
     Login1.UserName = cookie.Values["username"]; 

     //.Attributes.Add("value", cookie.Values["password"]); 
     Response.Cookies["myCookie"].Expires = DateTime.Now.AddDays(-1); 


    } 
} 

protected void Login1_LoggingIn(object sender, LoginCancelEventArgs e) 
{ 
    System.Web.UI.WebControls.Login Login1 = (System.Web.UI.WebControls.Login)LoginView1.FindControl("Login1"); 
    TextBox UserName = (TextBox)Login1.FindControl("UserName"); 

    //Check to see if the current user exists 
    if (Membership.GetUser(Login1.UserName) != null) 
    { 
     //Check to see if the user is currently locked out 
     if (Membership.GetUser(Login1.UserName).IsLockedOut) 
     { 
      //Get the last lockout date from the user 
      DateTime lastLockout = Membership.GetUser(Login1.UserName).LastLockoutDate; 
      Response.Write(lastLockout.ToString()); 
      //Calculate the time the user should be unlocked 
      DateTime unlockDate = lastLockout.AddMinutes(Membership.PasswordAttemptWindow); 

      //Check to see if it is time to unlock the user 
      if (DateTime.Now > unlockDate) 
       Membership.GetUser(Login1.UserName).UnlockUser(); 
     } 
    } 


} 


protected void Login1_Authenticate(object sender, AuthenticateEventArgs e) 
{ 
    System.Web.UI.WebControls.Login Login1 = (System.Web.UI.WebControls.Login)LoginView1.FindControl("Login1"); 
    TextBox UserName = (TextBox)Login1.FindControl("UserName"); 

    Response.Cookies.Add(new HttpCookie("UserName", Login1.UserName)); 
    CheckBox RememberMe = LoginView1.FindControl("RememberMe") as CheckBox; 
    //CheckBox RememberMe = (CheckBox).Login1.FindControl("RememberMe"); 

    HttpCookie myCookie = new HttpCookie("myCookie"); 
    if (RememberMe.Checked == true) 
    { 
     myCookie.Values.Add("username", Login1.UserName); 
     myCookie.Expires = DateTime.Now.AddDays(15); 
     Response.Cookies.Add(myCookie); 
    } 

} 


protected void Login1_LoginError(object sender, EventArgs e) 
{ 
    System.Web.UI.WebControls.Login Login1 = (System.Web.UI.WebControls.Login)LoginView1.FindControl("Login1"); 
    TextBox UserName = (TextBox)Login1.FindControl("UserName"); 
    Literal FailureText = (Literal)Login1.FindControl("FailureText"); 


    //There was a problem logging in the user 
    //See if this user exists in the database 

    MembershipUser userInfo = Membership.GetUser(Login1.UserName); 

    if (userInfo == null) 
    { 
     //The user entered an invalid username... 

     Login1.FailureText = "There is no user in the database with the username " + UserName.Text; 
    } 
    else 
    { 
     //See if the user is locked out or not approved 
     if (!userInfo.IsApproved) 

      Login1.FailureText = "When you created your account you were sent an email with steps to verify your account. You must follow these steps before you can log into the site."; 

     else if (userInfo.IsLockedOut) 

      Login1.FailureText = "Your account has been temporary locked due to a maximum number of incorrect login attempts."; 

     else 

      //The password was incorrect (don't show anything, the Login control already describes the problem) 
      Login1.FailureText = string.Empty; 

    } 
} 
+0

好心地调试你的项目,并找出在哪个地方确切的错误发生?如果它是由于引用引起的,那么应该指定在Codebehind中访问的每个控件的ClientIDMode属性为Static。 – 2012-07-08 17:32:18

+0

[在.NET中是什么是NullReferenceException?]的可能重复(http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net) – 2012-07-08 19:38:05

回答

1

在您的代码隐藏文件,请尝试用下面的代码替换Login1_Authenticate方法:

protected void Login1_Authenticate(object sender, AuthenticateEventArgs e) 
{ 
    System.Web.UI.WebControls.Login Login1 = (System.Web.UI.WebControls.Login)LoginView1.FindControl("Login1"); 
    TextBox UserName = (TextBox)Login1.FindControl("UserName"); 

    Response.Cookies.Add(new HttpCookie("UserName", Login1.UserName)); 

    // IMPORTANT: Notice that LoginView1 is changed to Login1 
    CheckBox RememberMe = Login1.FindControl("RememberMe") as CheckBox; 

    HttpCookie myCookie = new HttpCookie("myCookie"); 
    if (RememberMe.Checked == true) 
    { 
     myCookie.Values.Add("username", Login1.UserName); 
     myCookie.Expires = DateTime.Now.AddDays(15); 
     Response.Cookies.Add(myCookie); 
    } 

} 

我以为你是关系到一个事实,即FindControl方法不分层搜索问题 - 也就是说,它只会找到一个直接包含在父代中的子控件。它不会搜索图层。

就您而言,该复选框包含在Login1之内,而该复选框又是LoginView1的孩子。所以你需要在Login1内搜索,而不是LoginView1

0
CheckBox RememberMe = LoginView1.FindControl("RememberMe") as CheckBox; 

您正在使用“RememberMe”ID找到您的复选框。但请检查此复选框在您的网页上是否具有完全相同的ID。 ASP.NET默认不生成“干净”ID - 它看起来像ctl00 $ RemeberMe

0

如果问题归因于复选框引用,请尝试此操作。如果您使用的是.NET Framework 4,则将复选框的ClientIDMode属性设置为静态。 ClientIDMode="Static"

相关问题