MVC 用户身份验证(FormsAuthentication、Cookie、Session)

本文详细介绍了在MVC框架中如何使用FormsAuthentication进行用户身份验证,探讨了登录验证后服务器如何通过cookie回发验证信息。同时,文章也涉及到了Cookie的使用方法,包括登录设置、权限判断和退出操作的示例代码。最后提到了Session的使用,并提及MVC拦截器中的授权特性AuthorizeAttribute。
摘要由CSDN通过智能技术生成

一、FormsAuthentication

        解释:当用户登录时,服务器为确认客户端通过验证要通过cookie向客户端写验证(Authenticat)信息,
                   在登录页面刚验证完成后服务器还没有把cookie 回发到Client,所以会没有值,
                   当服务器第二次Response的时候,就会从客户端读取Cookie,要想有此Cookie还要在web.config文件中配置相应的参数

        /// <summary>
        /// 存入Form身份验证票证
        /// </summary>
        /// <returns></returns>
        public static void  SetFormAuthenti()
        {
            //如果为 true,则创建持久 Cookie(跨浏览器会话保存的 Cookie)
            FormsAuthentication.SetAuthCookie("存入Form身份验证票证", true);        
        }

        /// <summary>
        /// 获得Form身份验证票证
        /// </summary>
        /// <returns></returns>
        public static string GetFormAuthenti()
        {
            string str = "";
            if (HttpContext.Current.User.Identity.IsAuthenticated)//用户是否验证过
            {
                str = HttpContext.Current.User.Identity.Name;//获取用户名
            }
            return str;
        }

        /// <summary>
        /// 从浏览器中删除Form身份验证票证
        /// </summary>
        public static void DelFormAuthenti()
        {
            FormsAuthentication.SignOut();
        }


 

 

二、Cookie

            //存Cookie
            HttpCookie SetCookie = new HttpCookie("ckName");
            SetCookie["id"] = "100001271";
            Response.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

tiz198183

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值