.net MVC使用Session验证用户登录(转载)
2024-09-01 02:04:12
.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
最新文章
- 应用r.js来优化你的前端
- Wireshark设置interface 时提示“There are no interfaces on which a capture can be done ”
- .NET/ASP.NET Routing路由(深入解析路由系统架构原理)
- python中main()函数写法
- UVa 101 - The Blocks Problem(积木问题,指令操作)
- caca393刷PTP教程
- MVC部署 - 错误集锦
- android NDk环境编译总结
- Makefile中=、:=、+=、?=的区别
- hdu4722Good Numbers(dp)
- 求数列的和 AC 杭电
- 共享参数ContentProvider 类与数据库绑定,如何通过共享参数测试类,测试数据库的增删改查功能
- ##DAY15——UICollectionView
- 【原创】java NIO FileChannel 学习笔记 新建一个FileChannel
- TOJ 4120 Zombies VS Plants
- sql 语句-初级进阶(二)
- JVM调优日志解析分析
- 网络测试工具 - QCheck
- WEB返回顶部效果
- Linux Shell 下载网站指定文件
热门文章
- vue.js项目nginx部署
- 网页中的数据的4个处理方式:CRUD(Creat, Retrive, Update, Delete)
- Apollo配置管理系统使用
- MySQL 基础--字符类型
- 改善Python 程序的 91 个建议
- 从一个集合中查找最大最小的N个元素——Python heapq 堆数据结构
- Linux学习笔记之十一————Linux常用服务器构建之ssh和scp
- 一个关于margin-top的问题
- 【转】php结合redis实现高并发下的抢购、秒杀功能
- salesforce lightning零基础学习(五) 事件阶段(component events phase)