且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

保持登录用户的轨道

更新时间:2023-12-04 10:47:52

验证用户凭据后,你可以有一个code,如:

After validating the user credentials you can have a code like:

public void SignIn(string userName, bool createPersistentCookie)
{
    int timeout = createPersistentCookie ? 43200 : 30; //43200 = 1 month
    var ticket = new FormsAuthenticationTicket(userName, createPersistentCookie, timeout);
    string encrypted = FormsAuthentication.Encrypt(ticket);
    var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted);
    cookie.Expires = System.DateTime.Now.AddMinutes(timeout);
    HttpContext.Current.Response.Cookies.Add(cookie);
}

所以你的code可以是这样的:

So your code can be like this:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult LogOn(string userName, string passwd, bool rememberMe)
{
    //ValidateLogOn is your code for validating user credentials
    if (!ValidateLogOn(userName, passwd))
    {
        //Show error message, invalid login, etc.
        //return View(someViewModelHere);
    }

    SignIn(userName, rememberMe);

    return RedirectToAction("Home", "Index");
}

在从登录的用户的后续请求,HttpContext.User.Identity.Name应该包含登录用户的用户名。

In subsequent requests from the logged in user, HttpContext.User.Identity.Name should contain the user name of the logged in user.

祺!