.net MVC使用Session验证用户登录(转载)

 .net MVC使用Session验证用户登录

 

用最简单的Session方式记录用户登录状态

1.添加DefaultController控制器,重写OnActionExecuting方法,每次访问控制器前触发

复制代码
复制代码
    public class DefaultController : Controller
    {
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
            var controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;

            var userName = Session["UserName"] as String;
            if (String.IsNullOrEmpty(userName))
            {
                //重定向至登录页面
                filterContext.Result = RedirectToAction("Index", "Login", new { url = Request.RawUrl});
                return;
            }

        }
    }
复制代码
复制代码

2.登录控制器

复制代码
复制代码
    public class LoginController : Controller
    {
        // GET: Login
        public ActionResult Index(string ReturnUrl)
        {
            if (Session["UserName"] != null)
            {
                return RedirectToAction("Index", "Home");
            }
            ViewBag.Url = ReturnUrl;
            return View();
        }

        [HttpPost]
        public ActionResult Index(string name, string password, string returnUrl)
        {
            /*
                添加验证用户名密码代码
            */
            Session["UserName"] = name;
            if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }

        // POST: /Account/LogOff
        [HttpPost]
        public ActionResult LogOff()
        {
            Session["UserName"] = null;
            return RedirectToAction("Index", "Home");
        }
    }
复制代码
复制代码

3.需要验证的控制器继承DefaultController

复制代码
复制代码
    public class HomeController : DefaultController
    {
        public ActionResult Index()
        {
            return View();
        }
    }
复制代码
复制代码

 


这种方式适合比较小的项目
优点:简单,易开发
缺点:无法记录登录状态,而且Session方式容易丢失
转载来源:https://www.cnblogs.com/pengdylan/p/6421440.html
posted @   hao_1234_1234  阅读(1421)  评论(1编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示