我就是这样做的
public class MyAuthentication
{
public static HttpCookie GetAuthenticationCookie(LoginModel model, bool persistLogin)
{
// userData storing data in ticktet and then cookie
JavaScriptSerializer js = new JavaScriptSerializer();
var userData = js.Serialize(model);
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
1,
"akash",
DateTime.Now,
DateTime.Now.AddHours(1),
persistLogin,
userData);
string encTicket = FormsAuthentication.Encrypt(authTicket);
HttpCookie cookie= new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
cookie.Expires = authTicket.Expiration; //must do it for cookie expiration
return cookie;
}
internal static bool Login(string UserName, string Password)
{
//UserName="akash" Password="akash"
//check can be done by DB
if (UserName== "akash" && Password == "akash")
return true;
else
return false;
}
}
and then
[HttpGet]
[AllowAnonymous]
public ActionResult Login()
{
//ViewBag.Message = "Your contact page.";
HttpCookie cookie = Request.Cookies[FormsAuthentication.FormsCookieName];
// var ek = cookie.Value;
try
{
//some times no cookie in browser
JavaScriptSerializer js = new JavaScriptSerializer();
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
//string data = ticket.UserData;
LoginModel model = js.Deserialize<LoginModel>(ticket.UserData);
if (MyAuthentication.Login(model.UserName, model.Password) == true)
{
RedirectToAction("Index", "Home");
}
}
catch
{
}
return View();
您可以在 Global.asax 或授权过滤器上检查它。
确保你有 web.config 有
<authentication mode="Forms">
<forms defaultUrl="/Home/Login" loginUrl="/home/Login" timeout="2880">
</forms>
</authentication>
和所有控制器之前的 [Authorize] 属性。