1.创建登陆的控制器和视图,实现登陆基本功能
2.创建视图模型,并在Action里面引用。
3.创建一个接口两个类,那个IUserPricipal接口要实现IPrincipal接口,UserPricipal类需要继承这个接口,然后去初始化IIdentity这个接口,UserPricipalModel类则是返回用户输出的Cookie的数据模型。
具体代码:
两个类一个接口:
interface ICustomPrincipal : IPrincipal
{
UserViewModel User { get; set; }
}
public class CustomPriceipal : ICustomPrincipal
{
public IIdentity Identity { get; private set; }
public bool IsInRole(string role)
{
return false;
}
public CustomPriceipal(string email)
{
this.Identity = new GenericIdentity(email);
}
public bool IsAdmin { get; set; } = false;
public string UserName { get; set; }
public UserViewModel User { get; set; }
}
public class CustomPrincipalSerializeModel
{
public string UserName { get; set; }
public bool IsAdmin { get; set; }
public UserViewModel User { get; set; }
}
Action代码 :
[HttpPost]
public ActionResult Login(UserViewModel model)
{
if (model.Password == "" || model.UserName == "")
{
return View(model);
}
CustomPrincipalSerializeModel serializeModel = new CustomPrincipalSerializeModel();
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializeModel.User = model;
serializeModel.UserName = model.UserName;
string userData = serializer.Serialize(serializeModel);
var ticket = new FormsAuthenticationTicket(2, model.UserName, DateTime.Now, DateTime.Now.AddMinutes(1), false, userData);
string encryptTickey = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName,encryptTickey);
Response.Cookies.Remove(cookie.Name);
Response.Cookies.Add(cookie);
return Redirect("/Home/Index");
}
Global文件代码:
protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
{
HttpCookie cookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if(cookie!=null)
{
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
if (ticket != null && !string.IsNullOrEmpty(ticket.UserData))
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
CustomPrincipalSerializeModel serializeModel = serializer.Deserialize<CustomPrincipalSerializeModel>(ticket.UserData);
CustomPriceipal newUser = new CustomPriceipal(ticket.Name);
newUser.User = serializeModel.User;
newUser.UserName = serializeModel.UserName;
newUser.IsAdmin = serializeModel.IsAdmin;
HttpContext.Current.User = newUser;
}
}
}