本文主要是介绍使用httpmodule验证用户登录,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
当网站要验证用户是否登录时,每个页面都进行验证,实在是一件费时费力的事情,当需要修改时,那更是纯粹的浪费体力。
所以,我们可以采取当用户请求网站时,每个页面都进行验证,这就涉及到页面的生命周期。
首先,要修改配置文件,在web.config配置文件中增加一节
<!--配置module节--><httpModules><add name="MyModules" type="PetShop.MyModule,PetShop"/></httpModules>
其次是要写验证了,写一个类继承System.Web.IHttpModule接口,然后在委托中追加方法来进行验证
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;namespace PetShop
{public class MyModule:System.Web.IHttpModule{public void Dispose(){throw new NotImplementedException();}public void Init(HttpApplication application){//注册事件application.AuthenticateRequest += new EventHandler(Application_AuthenticateRequest);}/// <summary>/// 验证是否已经登录,找cookie,如果cookie没有,为未验证/// </summary>/// <param name="sender"></param>/// <param name="e"></param>protected void Application_AuthenticateRequest(object sender, EventArgs e){ string name;// HttpApplication application=new HttpApplication();HttpContext context = HttpContext.Current;HttpCookie cookie= context.Request.Cookies["Ticket"];// HttpCookie cookie = application.Request.Cookies["Ticket"];if (cookie != null){string cookiestring = cookie.Value;System.Web.Security.FormsAuthenticationTicket ticket =System.Web.Security.FormsAuthentication.Decrypt(cookiestring);name= ticket.Name;//将ticket发送出去}else{name = string.Empty;}//使用httpcontext对象传递信息// HttpContext context = HttpContext.Current;// context.Items.Add("UserName", name);//创建一个表示用户标识的对象MyIdentity identity = new MyIdentity(name, "PetShop");//创建一个表示用户的对象MyPrincipal principal=new MyPrincipal(identity,new string[]{});context.Items.Add("User", principal);}}
}
在页面上,只需要从Context对象中获取相应的属性就好啦,Context.Items["User"]即可获取到用户对象
//获得上下文对象HttpContext context = this.Context;// string name= context.Items["UserName"] as string;System.Security.Principal.IPrincipal user=context.Items["User"] as System.Security.Principal.IPrincipal;if (!user.Identity.IsAuthenticated)lable1.InnerText = "请登录";elselable1.InnerText = user.Identity.Name + ",欢迎您回来";
用户登录时,需要把验证后的用户信息存入到票据中
if (isExist){//通过验证后,将用户的信息保存起来System.Web.Security.FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(2, username, DateTime.Now, DateTime.Now.AddDays(1), true, string.Empty);//序列化string ticketstring = System.Web.Security.FormsAuthentication.Encrypt(ticket);//将票据保存到cookieHttpCookie cookie = new HttpCookie("Ticket");cookie.Value = ticketstring;cookie.Expires.AddDays(1);//发送到浏览器的cookie保存起来this.Response.Cookies.Add(cookie);Response.Redirect("Default.aspx");}
这篇关于使用httpmodule验证用户登录的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!