国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > .NET > 正文

.net MVC使用Session驗證用戶登錄(4)

2024-07-10 12:48:47
字體:
來源:轉載
供稿:網友

用最簡單的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("http://") && !returnUrl.StartsWith("http:///"))      {        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方式容易丟失

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持錯新站長站。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 聊城市| 陆川县| 宣化县| 西乌珠穆沁旗| 潞西市| 浑源县| 郧西县| 郓城县| 莎车县| 冷水江市| 德钦县| 全椒县| 新闻| 泸州市| 贡嘎县| 洛南县| 田阳县| 陈巴尔虎旗| 临桂县| 巢湖市| 宜兰县| 会泽县| 花莲市| 宁强县| 射阳县| 金堂县| 深泽县| 富川| 平陆县| 瓦房店市| 彰化市| 南川市| 辰溪县| 天门市| 钟祥市| 怀柔区| 和林格尔县| 澎湖县| 承德县| 景宁| 天柱县|