登录后重定向不适合我

时间:2015-06-11 12:33:27

标签: c# asp.net

我正在创建一个页面,一旦登录进行身份验证,它就会重定向到目标网页。我使用了登录向导。单击导航栏中的任何链接(如果未登录),它将重定向到单独的注册页面。发生的事情是,一旦我登录,它就会直接转到注册页面而不是登录页面。我包括登录页面和web.config的代码。顺便说一下,我正在使用Bootstrap。

登录页面

<add name="SignupDB" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=&quot;C:\Users\admin\Documents\Visual Studio 2010\WebSites\mysite\App_Data\DB1.mdb&quot;;Persist Security Info=True;Jet OLEDB:Database Password=mypassword" providerName="System.Data.OleDb"/>
</connectionStrings>
<system.web>
<authentication mode="Forms">
    <forms loginUrl="RegPage.aspx" name="login" protection="Validation" defaultUrl="LandingPage.aspx" cookieless="UseCookies" timeout="200" enableCrossAppRedirects="true"/>
</authentication>
<authorization>
    <deny users="?"/>
</authorization>

的web.config:

ListViewActivity

1 个答案:

答案 0 :(得分:1)

我认为重定向不是你的问题。问题是您没有使用表单身份验证进行日志记录,因此当您通过表单身份验证重定向到任何受保护的页面时,它会将您重定向回登录页面。看看这个方法,初始化表单身份验证。

private void Authenticate(string login)
{
  FormsAuthentication.Initialize();

  var ticket = new FormsAuthenticationTicket(1,
                                             login,
                                             DateTime.Now,
                                             DateTime.Now.AddHours(3), // time of user's session .. add more if you need
                                             false,
                                             null);

  var encryptedTicket = FormsAuthentication.Encrypt(ticket);

  if (!FormsAuthentication.CookiesSupported)
  {
      FormsAuthentication.SetAuthCookie(encryptedTicket, false);
  }
  else
  {
      HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);

      authCookie.Expires = ticket.Expiration;

      System.Web.HttpContext.Current.Response.Cookies.Add(authCookie);
  }  
}

您可以在登录成功时调用它,例如:

protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
    Boolean blnresult;
    blnresult = false;

    blnresult = Authentication(Login1.UserName, Login1.Password);
    if(blnresult)
    {
        e.Authenticated = true;

        // authenticate using Forms Authentication
        Authenticate(Login1.UserName);

        Response.Redirect("LandingPage.aspx");
    }
    else
    {
        e.Authenticated = false;
    }
}

我还对您的数据库访问做了一些改进,以确保您关闭了数据库连接:

protected static bool Authentication(string usernames, string passwords)
{
    string sqlcmd = "SELECT UName, Pwd from  [SignupDB] where UName = '" + usernames + "' and Pwd = '" + passwords + "'";

    using(OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|/DB1.mdb;Persist Security Info=True;Jet OLEDB:Database Password=mypassword"))
    {
      con.Open();
      OleDbCommand cmd = new OleDbCommand(sqlcmd, con);
      using(OleDbDataReader reader = cmd.ExecuteReader())
      {
        if (reader.Read())
            return true;
        else
            return false;

      }
    }    
}