对于有些项目我们希望当用户登录了,才可以让他看到里面的内容,没有登录的时候,我们把用户拦截到登录页面,进行登录。网站开发中,为了保存用户信息,我们就会用到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,就放行,session
为 null
,让它重定向到登录页面。
③ 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/
,回调到登录页面。