分布视图

@if (Request.IsAuthenticated)
{
<text>
你好,@Html.ActionLink(User.Identity.Name, "Manage", "Admin", routeValues: null, htmlAttributes: new { @class = "username", title = "管理" })!
@using (Html.BeginForm("LoginOut", "Account", FormMethod.Post, new { id = "LoginOutForm" }))
{
@Html.AntiForgeryToken()
<a href="javascript:document.getElementById('LoginOutForm').submit()">注销</a>
}
</text>
}
else
{ <text>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<p>
@Html.ActionLink("登录", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })
@Html.ActionLink("注册", "Register", "Account", routeValues: null, htmlAttributes: new { id = "registerLink" })
</p>
}
</text>
}

登录控制器代码

 

MsgContext db = new MsgContext();

 

[HttpGet]
public ActionResult Login()
{
return View();
}

 

 

[HttpPost]
public ActionResult Login(Login admin)
{
var user = db.Admins.Where(a => a.UserName == admin.UserName
&& a.Password == admin.Password).FirstOrDefault();
if (user != null)
{
//创建一个新的票据,将用户的名字记入ticket的userdata
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
1, user.UserName, DateTime.Now, DateTime.Now.AddMinutes(20),
false, user.AdminRole.ToString());
//将票据加密
string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
//将加密后的票据保存为cookie
System.Web.HttpCookie authCookie = new System.Web.HttpCookie
(FormsAuthentication.FormsCookieName, encryptedTicket);
//使用加入了userdata的新cookie
System.Web.HttpContext.Current.Response.Cookies.Add(authCookie);
return RedirectToAction("Index", "Admin");
}
return View();
}

posted @ 2016-01-05 10:16  butterfly小d  阅读(138)  评论(0编辑  收藏  举报