Sau khi chứng thực thông tin người dùng, bạn có thể có một mã như:
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);
}
Vì vậy, mã của bạn có thể như thế này:
[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");
}
Trong yêu cầu tiếp theo từ người dùng đăng nhập, HttpContext.User .Identity.Name phải chứa tên người dùng của người dùng đã đăng nhập.
Trân trọng!
Tiếng Anh của bạn rất tốt :) – roryf
Nếu bạn muốn tùy chỉnh xác thực ASP.NET, thì bạn * nên * sử dụng nhà cung cấp thành viên, ngay cả khi bạn phải tự viết tất cả. http://blogs.teamb.com/craigstuntz/2009/09/09/38390/ –