解决方法
验证用户凭据后,您可以使用以下代码:
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); }
所以你的代码可以是这样的:
[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应包含登录用户的用户名.
问候!