第一次登陆不行,第二次登陆可以

First login not work, but second login is work

我正在尝试学习 MVC 编码,但我遇到了最后一个小问题。第一次登录不工作,但第二次登录工作。每次都是这样。

我的控制器代码:

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

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

我的索引查看代码:

@section Login{

    @if (Session["UserID"] == null)
    {
        <li><a href="/Home/Login"><span class="glyphicon glyphicon-log-in"> </span> &nbsp Log In</a></li>
        <li><a href="/Home/Register"><span class="glyphicon glyphicon-plus"> </span> Create an Account</a></li>
    }
    else
    {    
        int userID = (int)Session["UserID"];
        <li><a href="/Home/UserDetail/@userID"><span class="glyphicon glyphicon-user"> </span> User Detail</a></li>
        <li><a href="/Home/Orders"><span class="glyphicon glyphicon-gift"> </span> &nbsp Orders</a></li>
        <li><a href="/Home/LogOut"><span class="glyphicon glyphicon-log-out"> </span> &nbsp Log Out</a></li>
    }
}

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

感谢任何人的帮助,很抱歉我的英语不好。

好的,我这样解决了问题

[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
        }                      
    }