只是想知道在 mvc3 中处理登录/用户身份验证的最佳实践是什么。最好使用内置的成员资格,例如:
[HttpPost]
public ActionResult Register(RegisterUser model)
{
if (ModelState.IsValid)
{
// Attempt to register the user
MembershipCreateStatus createStatus;
Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus);
if (createStatus == MembershipCreateStatus.Success)
{
FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);
return RedirectToAction("Index","User");
}
else
{
ModelState.AddModelError("", ErrorCodeToString(createStatus));
}
}
return View(model);
}
或者更简单和自定义的东西,例如制作自己的 cookie 以避免每次都使用预打包的数据库结构?
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1,
user.UserName,
DateTime.Now,
DateTime.Now.AddMinutes(10),
false,
null);
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
this.Response.Cookies.Add(cookie);