1.控制器上面用 [Authorize] 属性标识,表示当前控制器内的所有函数需要用户认证才能访问
2.函数上面用 [AllowAnonymous] 属性标识,表示当前函数不需要用户认证可以直接访问
3.函数上面使用 [NonAction] 属性标识,表示此方法不作为控制器函数
代码:
1.HomeController
namespace TestMVC.Controllers { [Authorize] public class HomeController : Controller { // GET: Home public ActionResult Index() { return View(); } [AllowAnonymous] public ActionResult Login() { return View(); } [AllowAnonymous] [HttpPost] public ActionResult DoLogin(UserDetail user) { if (IsValidUser(user)) { //注册账户 FormsAuthentication.SetAuthCookie(user.UserName, false); return RedirectToAction("Index", "Home"); } else { //错误消息提示 ModelState.AddModelError("ErrorMessage", "用户名或密码错误!"); return View("Login"); } } [NonAction] public bool IsValidUser(UserDetail user) { if (user.UserName == "admin" && user.Password == "admin") return true; else return false; } } }
2.Home/Index.cshtml
@{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> </head> <body> <div> <h1>首页</h1> </div> </body> </html>
3.Home/Login.cshtml
@model TestMVC.Models.UserDetail @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Login</title> </head> <body> <div> @Html.ValidationMessage("ErrorMessage", new { style = "color:red;" }) @using(Html.BeginForm("DoLogin","Home",FormMethod.Post)){ @Html.LabelFor(u=>u.UserName) @Html.TextBoxFor(u=>u.UserName) <br /> @Html.LabelFor(u => u.Password) @Html.TextBoxFor(u => u.Password) <br /> <input type="submit" value="登录" /> } </div> </body> </html>
4.Web.config配置,当验证登录没有通过时跳转的Home/Login页面