MVC Filters
demo
Controll:AuthFiltersController
action Welcome添加了系统自带的过滤器Authorize
public class AuthFiltersController : Controller { // // GET: /AuthFilters/ public ActionResult Index() { return View(); } [Authorize] public ActionResult Welcome() { return View(); } }
Controll:AccountController 用户登录和注销
webconfig配置中的:
<authentication mode="Forms"> <forms loginUrl="~/Account/Login" timeout="2880" /> </authentication>
public class AccountController : Controller { // // GET: /Account/ public ActionResult Index() { return View(); } public ActionResult Login() { filter.Models.LogOnViewModel mode = new Models.LogOnViewModel(); return View(); } [HttpPost] public ActionResult Login(filter.Models.LogOnViewModel mode) { if (mode.UserName.Trim() == mode.Password.Trim()) //伪代码,只要输入的用户名和密码一样就过 { if (mode.RememberMe) FormsAuthentication.SetAuthCookie(mode.UserName, true); //2880分钟有效期的cookie else FormsAuthentication.SetAuthCookie(mode.UserName, false); //会话cookie return RedirectToAction("Welcome", "AuthFilters"); } else return View(mode); } public ActionResult Logout() { Session.Abandon(); FormsAuthentication.SignOut(); return RedirectToAction("Login", "Account"); } }
welcome页面:
@{ ViewBag.Title = "Welcome"; } <h2>Welcome</h2> @{ if (Request.IsAuthenticated) { <text>Hello,</text> @User.Identity.Name <span> @Html.ActionLink("注销", "Logout", "Account")</span> } } <p />
login页面:
@model filter.Models.LogOnViewModel @{ ViewBag.Title = "Login"; } <h2>Login</h2> @using (Html.BeginForm()) { @Html.AntiForgeryToken() @Html.ValidationSummary(true) <fieldset> <legend>LogOnViewModel</legend> <div class="editor-label"> 用户名 </div> <div class="editor-field"> @Html.EditorFor(model => model.UserName) </div> <div class="editor-label"> 密码 </div> <div class="editor-field"> @Html.EditorFor(model => model.Password) </div> <div class="editor-label"> 记住我 </div> <div class="editor-field"> @Html.CheckBoxFor(model => model.RememberMe) </div> <p><input type="submit" value="登录" /></p> </fieldset> } <div> @Html.ActionLink("Back to List", "Index") </div> @section Scripts { @Scripts.Render("~/bundles/jqueryval") }
逻辑:访问Authfilters/Welcome 页面,如果没有登录在跳转到Account/Login页面。
****** FormsAuthentication.SetAuthCookie(mode.UserName, true) 系统自带写入cookie