.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

最新文章

  1. 应用r.js来优化你的前端
  2. Wireshark设置interface 时提示“There are no interfaces on which a capture can be done ”
  3. .NET/ASP.NET Routing路由(深入解析路由系统架构原理)
  4. python中main()函数写法
  5. UVa 101 - The Blocks Problem(积木问题,指令操作)
  6. caca393刷PTP教程
  7. MVC部署 - 错误集锦
  8. android NDk环境编译总结
  9. Makefile中=、:=、+=、?=的区别
  10. hdu4722Good Numbers(dp)
  11. 求数列的和 AC 杭电
  12. 共享参数ContentProvider 类与数据库绑定,如何通过共享参数测试类,测试数据库的增删改查功能
  13. ##DAY15——UICollectionView
  14. 【原创】java NIO FileChannel 学习笔记 新建一个FileChannel
  15. TOJ 4120 Zombies VS Plants
  16. sql 语句-初级进阶(二)
  17. JVM调优日志解析分析
  18. 网络测试工具 - QCheck
  19. WEB返回顶部效果
  20. Linux Shell 下载网站指定文件

热门文章

  1. vue.js项目nginx部署
  2. 网页中的数据的4个处理方式:CRUD(Creat, Retrive, Update, Delete)
  3. Apollo配置管理系统使用
  4. MySQL 基础--字符类型
  5. 改善Python 程序的 91 个建议
  6. 从一个集合中查找最大最小的N个元素——Python heapq 堆数据结构
  7. Linux学习笔记之十一————Linux常用服务器构建之ssh和scp
  8. 一个关于margin-top的问题
  9. 【转】php结合redis实现高并发下的抢购、秒杀功能
  10. salesforce lightning零基础学习(五) 事件阶段(component events phase)