C# Session 拦截 未登录用户 拦截到登录页面

对于有些项目我们希望当用户登录了,才可以让他看到里面的内容,没有登录的时候,我们把用户拦截到登录页面,进行登录。网站开发中,为了保存用户信息,我们就会用到Session

简单 Session 拦截案例

1、创建 ASP.NET 应用程序,主要代码如下:
HomeController.cs

using System.Web.Mvc;

using Test.BLL;
using Test.Utility;

namespace TestIntercept.Controllers
{
    [CustomerActionFilter]  // 自定义的拦截器
    public class HomeController : Controller
    {
        [HttpGet]
        public JsonResult Index()
        {
            return Json(PersonBLL.GetList(), JsonRequestBehavior.AllowGet);
        }
    }
}

CustomerActionFilter.cs 自定义拦截器

using System.Web.Mvc;

namespace Test.Utility
{
    public class CustomerActionFilter : ActionFilterAttribute, IActionFilter
    {
    	// 在执行控制器方法之前执行
        void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
        {
            var username = filterContext.HttpContext.Session["username"];

            if (username != null)
                OnActionExecuting(filterContext);
            else
                filterContext.HttpContext.Response.Redirect("~/Person/Login");
        }
    }
}

说明: CustomerActionFilter 实现两个筛选器,重写 IActionFilter 筛选器中的OnActionExecuting 方法,这个方法在执行操作方法之前调用。在这个方法中进行业务判断,如果请求的 session 有 username,就放行,sessionnull,让它重定向到登录页面。

PersonController.cs

using System.Web.Mvc;
using System.Collections.Generic;

namespace Test.App.Controllers
{
    public class PersonController : Controller
    {
        [HttpGet]
        public JsonResult Login()
        {
            Dictionary<string, string> message = new Dictionary<string, string>();
            message.Add("message", "请登录");

            return Json(message, JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public void DoLogin(string username)
        {
            Session["username"] = username;
            Response.Redirect("~/Home/Index");
        }

        [HttpGet]
        public JsonResult Loginout()
        {
            Session["username"] = null;

            Dictionary<string, string> paras = new Dictionary<string, string>();
            paras.Add("stateCode", "0");
            paras.Add("message", "退出成功");

            return Json(paras, JsonRequestBehavior.AllowGet);
        }
    }
}

说明: Login() 向页面返回需要登录的信息。DoLogin() 模拟登录,在请求这个方法的时候,把用户名放到 Session 中,然后再重定向到信息页面。Loginout()模拟退出,退出的时候,将 Session中的 username 置为 null

2、案例测试
① 直接https://localhost:44349/访问,会跳到登录页面。
在这里插入图片描述
② 请求 localhost:44349/Person/DoLogin?username=haha 进行登录,登录成功会重定向到信息页面。
在这里插入图片描述
③ 请求 https://localhost:44349/Person/Loginout 退出登录,将 Session 中的用户名置为 null,重新访问 https://localhost:44349/,回调到登录页面。
在这里插入图片描述
在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值