ASP.NET MVC 基礎入門 http://www.cnblogs.com/liunlls/p/aspnetmvc_gettingstarted.html 設置預設啟動頁面 設置重定向配置(沒有登錄的匿名用戶將重定向到配置的地址) 設置控制器過濾器; 特性也可以只設置方法;下麵的代碼中,如果用戶 ...
ASP.NET MVC 基礎入門 http://www.cnblogs.com/liunlls/p/aspnetmvc_gettingstarted.html
設置預設啟動頁面
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Account", action = "Login", id = UrlParameter.Optional }
);
}
}
設置重定向配置(沒有登錄的匿名用戶將重定向到配置的地址)
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880"></forms>
</authentication>
設置控制器過濾器;Authorize
特性也可以只設置方法;下麵的代碼中,如果用戶沒有登錄,請求Home/UserCenter話會被定向到登錄界面(Account/Login)
//Authorize,過濾器(filter),禁止匿名訪問
[Authorize]
public class HomeController : Controller
{
//允許匿名用戶訪問
[AllowAnonymous]
public ActionResult Index()
{
return View();
}
public ActionResult UserCenter()
{
return View();
}
}
登錄數據模型,用的是VS自動生成的,可以根據自己的需求定製,包括數據驗證特性,可參考http://www.cnblogs.com/liunlls/p/aspnet_mvc_adding_validation.html
public class LoginViewModel
{
[Required]
[Display(Name = "賬號")]
public string Account { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "密碼")]
public string Password { get; set; }
[Display(Name = "記住我?")]
public bool RememberMe { get; set; }
}
登錄方法
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginViewModel model, string returnUrl)
{
if (!ModelState.IsValid)
{
return View(model);
}
//驗證賬號密碼
if (model.Account.Equals("admin") && model.Password.Equals("123456"))
{
string userData = new JavaScriptSerializer().Serialize(model);
//驗證票據
var ticket = new FormsAuthenticationTicket(1, model.Account, DateTime.Now,DateTime.Now.AddDays(COOKIE_EXPIRES), false, userData, FormsAuthentication.FormsCookiePath);
//加密
string encrypt = FormsAuthentication.Encrypt(ticket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypt);
if (model.RememberMe)
{
cookie.Expires = DateTime.Now.AddDays(COOKIE_EXPIRES);
}
//保存cookie
Response.Cookies.Remove(cookie.Name);
Response.Cookies.Add(cookie);
if (string.IsNullOrEmpty(returnUrl))
{
return RedirectToAction("Index","Home");
}
else
return Redirect(returnUrl);
}
else
{
ModelState.AddModelError("", "無效的登錄嘗試。");
return View(model);
}
}
註銷用戶方法
public ActionResult LoginOut()
{
FormsAuthentication.SignOut();
return Redirect(FormsAuthentication.LoginUrl);
}