首次登录不起作用,但第二次登录是有效的

时间:2017-02-18 11:15:20

标签: asp.net-mvc session login login-control

我正在尝试学习MVC编码,但我有一个小问题。首次登录不起作用,但第二次登录是有效的。它每次都是这样的。

我的控制器代码:

internal sealed class Configuration : DbMigrationsConfiguration<MyDbContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = true;

        SetSqlGenerator("System.Data.SqlClient", new FixedSqlServerMigrationSqlGenerator ());
    }
    ...
}

我在索引页面上使用此会话[“UserID”]来了解我已登录。

我的索引查看代码:

public ActionResult Login()
    {
        if (Session["UserID"] != null)
        {
            Response.Redirect("/Home/Index");
        }
        return View();
    }

[HttpPost]
public ActionResult Login(string txtUsername, string txtPassword)
    {            
        Customer loggedInUser = db.Customers.Where(x=> x.Username == txtUsername && x.Password == txtPassword).FirstOrDefault();
        if (loggedInUser == null)
        {
            Response.Write("<script>alert('Please check your username and password.')</script>");
            return View();
        }
        else
        {                
            Session["UserID"] = loggedInUser.ID;
            Response.Redirect("/Home/Index");
            return View();
        }                      
    }

我在VS上使用断点进行调查。在第一次登录尝试中,Session [“UserID”]填充控制器,但Session [“UserID”]在首次登录尝试时在Index View页面上看起来像null。我再试一次,这次Session [“UserID”]在索引视图页面上不为空。

感谢任何人的帮助,对不起我的英语不好。

1 个答案:

答案 0 :(得分:0)

好的,我已经用这种方式解决了这个问题

[HttpPost]
public ActionResult Login(string txtUsername, string txtPassword)
    {            
        Customer loggedInUser = db.Customers.Where(x=> x.Username == txtUsername && x.Password == txtPassword).FirstOrDefault();
        if (loggedInUser == null)
        {
            Response.Write("<script>alert('Please check your username and password.')</script>");
            return View();
        }
        else
        {                
            Session["UserID"] = loggedInUser.ID;
            //Response.Redirect("/Home/Index"); that's not good way
            return Redirect("/Home/Index"); //this is the good way
        }                      
    }