MVC简单用户登录授权认证

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;
        }
    }
}
View Code
复制代码

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>
View Code
复制代码

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>
View Code
复制代码

4.Web.config配置,当验证登录没有通过时跳转的Home/Login页面

posted @   不哼不哈  阅读(1010)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· 展开说说关于C#中ORM框架的用法!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
点击右上角即可分享
微信分享提示