public ActionResult LogOn(LogOnModel model, string returnUrl)
{
try
{
//ManageService 中定義了驗證用戶名的方法 VerifyUserLogon, 在之前的第四課中寫了如何去驗證用戶名密碼
ManageService _manageService = new ManageService();
if (ModelState.IsValid)
{
//判斷輸入的用戶名密碼是否正確
bool _isUserLogon = _manageService.VerifyUserLogOn(model.UserName, model.Password);
string role = "Admin";
if (_isUserLogon)
{
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, //版本
model.UserName, //用戶名
DateTime.Now, //時間
DateTime.Now.AddDays(2), //過期時間
false, //是否一直有效
role);
//將新的Ticket轉變爲Cookie值,並添加到Cookies集合中
string encTicket = FormsAuthentication.Encrypt(authTicket);
this.Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));
this.Response.Cookies.Add(new HttpCookie("role", role));
}
}
return RedirectToAction("Index", "Home");
// If we got this far, something failed, redisplay form
}
catch(Exception ex)
{
throw new Exception("Log on failed:" + ex.Message);
}
}