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

发布时间:2022-04-16 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了.net MVC使用Session验证用户登录(4)脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

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

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

脚本宝典总结

以上是脚本宝典为你收集整理的.net MVC使用Session验证用户登录(4)全部内容,希望文章能够帮你解决.net MVC使用Session验证用户登录(4)所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。