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

所属分类: 网络编程 / ASP.NET 阅读数: 1858
收藏 0 赞 0 分享

用最简单的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方式容易丢失

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

更多精彩内容其他人还在看

Asp.net中的mail的发送

Asp.net中的mail的发送
收藏 0 赞 0 分享

用ASP.Net实现文件的在线压缩和解压缩

用ASP.Net实现文件的在线压缩和解压缩
收藏 0 赞 0 分享

ASP.NET中文件上传下载方法集合

ASP.NET中文件上传下载方法集合
收藏 0 赞 0 分享

ASP.NET通过Remoting service上传文件

ASP.NET通过Remoting service上传文件
收藏 0 赞 0 分享

ASP.NET2.0服务器控件之Render方法

ASP.NET2.0服务器控件之Render方法
收藏 0 赞 0 分享

ASP.NET2.0 WebRource,开发微调按钮控件

ASP.NET2.0 WebRource,开发微调按钮控件
收藏 0 赞 0 分享

ASP.NET2.0新特性概述

ASP.NET2.0新特性概述
收藏 0 赞 0 分享

介绍几个ASP.NET中容易忽略但却很重要的方法函数

介绍几个ASP.NET中容易忽略但却很重要的方法函数
收藏 0 赞 0 分享

asp.net2.0如何加密数据库联接字符串

asp.net2.0如何加密数据库联接字符串
收藏 0 赞 0 分享

用.NET 2.0压缩/解压功能处理大型数据

用.NET 2.0压缩/解压功能处理大型数据
收藏 0 赞 0 分享
查看更多