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)
    {
    
    
        
    }
}

猜你喜欢

转载自blog.csdn.net/ryancao530/article/details/112361850
今日推荐