MVC简单用户登录授权认证_MVC如何验证用户登陆
2017-12-15 14:20:54 By: shinyuu
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页面
<system.web> <compilation debug="true" targetFramework="4.5" /> <httpRuntime targetFramework="4.5" /> <authentication mode="Forms"> <forms loginUrl="/Home/Login"></forms> </authentication> </system.web>
若资源对你有帮助,浏览后有很大收获,不妨小额打赏我一下、你的鼓励是维持我不断写博客最大动力。
想获取DD博客最新代码,你可以扫描下方的二维码,关注DD博客微信公众号(ddblogs)。
或者你也可以关注我的新浪微博,了解DD博客的最新动态:DD博客官方微博(dwtedx的微博)
如对资源有任何疑问或觉得仍然有很大的改善空间,可以对该博文进行评论,希望不吝赐教。
为保证及时回复,可以使用博客留言板给我留言: DD博客留言板(dwtedx的留言板)
感谢你的访问,祝你生活愉快、工作顺心、欢迎常来逛逛。
ligo 2021-02-22 16:48:27 1 评 | 回复
我调用 FormsAuthentication.SetAuthCookie(userName, false); 之后,控制器前面的[Authorize]仍然不能得到授权,当访问页面时,还是会跳到登录页面。是不是哪里还需要设置?