控制器:
private AdminUserService adminUserService = new AdminUserService();
// GET: Login
/// <summary>
/// 登录页面
/// </summary>
/// <returns></returns>
public ActionResult Login()
{
if (AdminUserContext.context.UserInfo_no != null)
{
return RedirectToAction("Index", "Home");
}
//再次浏览器判断是否有值
//var cookie = System.Web.HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
var name = this.User.Identity.IsAuthenticated ? this.User.Identity.Name : null;
if (name != null)
{
//获取存在的cookie
//var ticket = FormsAuthentication.Decrypt(cookie.Value);
//string userData = ticket.UserData;
if (!string.IsNullOrEmpty(name))
{
//存储在session里面
AdminUser adminInfo = new AdminUser();
adminInfo.Id = Convert.ToInt32(name.Split('&')[1]);
adminInfo.Name = name.Split('&')[0];
AdminUserContext.context.UserInfo_no = adminInfo;
return RedirectToAction("Index", "Home");
}
}
return View();
}
//登录
public JsonResult GetAdminUser(AdminUser adminUser, bool opr)
{
Opretation opretation = new Opretation();
//AdminUser user = adminUserService.ValidateLogin(adminUser);
AdminUser user = adminUserService.Query(a=>a.Name==adminUser.Name&&a.Password==adminUser.Password);
opretation.Success = user != null;
if (opretation.Success)
{
AdminUserContext.context.UserInfo_no = user;
if (opr)
{
//判断是否记住密码
string userData = user.Name + "&" + user.Id;
数据放入ticket
//FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, adminUser.Name, DateTime.Now, DateTime.Now.AddMinutes(60), false, userData);
数据加密
//string enyTicket = FormsAuthentication.Encrypt(ticket);
//HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, enyTicket);
//System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
FormsAuthentication.SetAuthCookie(userData, opretation.Success);
}
}
return Json(opretation);
}
前端页面:
<script type="text/javascript">
$(function () {
$("#entry_btn").click(function () {
if ($("#entry_name").val() == "") {
layer.alert('登录不能为空!', {
title: '提示框',
icon: 0,
});
} else if ($("#entry_password").val() == "") {
layer.alert('密码不能为空!', {
title: '提示框',
icon: 0,
});
} else{
var date = {};
date.Adminname = $("#entry_name").val();
date.pwd = $("#entry_password").val();
$.ajax({
type: "post",
url: "/Login/GetNameAndPwdLogin",
data: date,
success: function (data) {
if (data.success) {
layer.alert('登录成功!', {
title: '提示框',
icon: 1,
}),location.href = "/Home/index?Adminname="+date.Adminname;
layer.close(index);
}
else {
layer.alert('登录失败!', {
title: '提示框',
icon: 0,
});
}
}
})
}
});
});
</script>