ASP.Net MVC Session身份校验

ASP.Net MVC Session身份校验

Session的重要性

客户端每次向服务器发送请求,服务器都会生成该页面的实例。有时候,我们希望在不同的页面之间共享信息,比如用户登录状态等,于是,ASP.NET为我们提供了一个服务端的机制-Session。

需要注意,在ASP.NET中,Session只存在于action中,在controller构造函数中获取Session是行不通的。

Session如何工作

服务端的Session会保存每个客户端的信息到服务端内存中。
Session工作流程:

  1. 客户端向服务端发出请求
  2. 服务端响应客户端,并针对该客户端创建Session和唯一的Session ID
  3. 把Session ID作为key, Session内容作为value,以键值对形式存储到Session State Provider中
  4. 客户端带着专属的Session ID再次向服务端请求
  5. 服务端的Session机制根据客户端的Session ID,从Session State Provider中取出内容返回给客户端

Session优点:

  1. 跨页面维持用户状态、信息
  2. 使用方便,并且能存储任何类型
  3. 能保存每个客户端的信息
  4. 安全的、透明的

Session缺点:

  1. 因为Session是保存在服务端的内存中的,随着客户端请求的增多,很有可能影响到性能
  2. 在Web.conig中,sessionState节点的mode属性,如果设置为"StateServer"或"SQLServer",就必须为存储到Session中的对象打上[Serializable]。这样在存储、读取Session的时候,不断地序列化和反序列化,也会影响到性能

Session身份验证

namespace WebApplication.Controllers
{
    public class RegisterController : Controller
    {
        public ActionResult Index()
        {
        	return View();
        }
        
        public ActionResult Login()
        {
        	Session["Auth"] = true;
        	return RedirectToAction("Index");
        }
        
		public ActionResult Logout()
        {
        	Session["Auth"] = false;
        	return RedirectToAction("Index");
        }
       	
       	[AuthenticationFilter]
       	public ActionResult BackEnd()
       	{
       		return Content("进入后台");
       	}    
    }
}
public class AuthenticationFilterAttribute : ActionFilterAttribute, IAuthenticationFilter
{
    public void OnAuthentication(AuthenticationContext filterContext)
    {
        bool bRet = Convert.ToBoolean(filterContext.HttpContext.Session["Auth"]);
        if (!bRet)
        {
            filterContext.Result = new HttpUnauthorizedResult();
            return;
        }
        
    public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
    {
        
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值