ASP.NET MVC 用户登录Login

一.先来看个框架例子:(这个是网上收集到的)
 第一步:创建一个类库ClassLibrary831。
            第二步:编写一个类实现IHttpModule接口
                class TestModule:IHttpModule
                {
                    public void Dispose()
                    {
                    }
                    public void Init(HttpApplication context)
                    {
                    }
                } 
            第三步:在Init事件中注册EndRequest事件,并实现事件处理方法
               class TestModule:IHttpModule
                {
                    public void Dispose(){}
                    public void Init(HttpApplication context)
                    {
                        context.EndRequest += new EventHandler(context_EndRequest);
                    }
                    void context_EndRequest(object sender, EventArgs e)
                    {
                        HttpApplication ha = (HttpApplication)sender;
                        ha.Response.Write("<!--这是每个页面都会动态生成的文字。--grayworm-->");
                    }
                } 
            第四步:在Web.Conofig中注册一下这个HttpModule模块
          
<httpModules>
           <add name="TestModule" type="ClassLibrary831.TestModule,ClassLibrary831"></add>
          </httpModules> 
          name:模块名称,一般是类名
          type:有两部分组成,前半部分是命名空间和类名组成的全名,后半部分是程序集名称,如果类是直接放在App_Code文件夹中,那程序名称是App_Code。
                这样在Web站点是添加该类库的引用后,运行每个页面,会发现其源文件中都会加入“<!--这是每个页面都会动态生成的文字。--grayworm-->”这句话。同样的方法你也可以在其中加入JS代码。
       2、身份检查
            大家在作登录时,登录成功后,一般要把用户名放在Session中保存,在其它每一个页面的Page_Load事件中都检查Session中是否存在用户名,如果不存在就说明用户未登录,就不让其访问其中的内容。
            在比较大的程序中,这种做法实在是太笨拙,因为你几乎要在每一个页面中都加入检测Session的代码,导致难以开发和维护。下面我们看看如何使用HttpModule来减少我们的工作量
            由于在这里我们要用到Session中的内容,我们只能在AcquireRequestState和PreRequestHandlerExecute事件中编写代码,因为在HttpModule中只有这两事件中可以访问Session。这里我们选择PreRequestHandlerExecute事件编写代码。
            第一步:创建一个类库ClassLibrary831。
            第二步:编写一个类实现IHttpModule接口
                class TestModule:IHttpModule
                {
                    public void Dispose()
                    {
                    }
                    public void Init(HttpApplication context)
                    {
                    }
                } 
            第三步:在Init事件中注册PreRequestHandlerExecute事件,并实现事件处理方法
               class AuthenticModule:IHttpModule
                {
                    public void Dispose(){}
                    public void Init(HttpApplication context)
                    {
                        context.PreRequestHandlerExecute += new EventHandler(context_PreRequestHandlerExecute);
                    }
                    void context_PreRequestHandlerExecute(object sender, EventArgs e)
                    {
                        HttpApplication ha = (HttpApplication)sender;
                        string path = ha.Context.Request.Url.ToString();
                        int n = path.ToLower().IndexOf("Login.aspx"); 
                        if (n == -1) //是否是登录页面,不是登录页面的话则进入{}
                        {
                            if (ha.Context.Session["user"] == null) //是否Session中有用户名,若是空的话,转向登录页。
                            {
                                ha.Context.Response.Redirect("Login.aspx?source=" + path);
                            }
                        }
                    }
                } 
            第四步:在Login.aspx页面的“登录”按钮中加入下面代码
                protected void Button1_Click(object sender, EventArgs e)
                {
                    if(true)    //判断用户名密码是否正确
                    { 
                        if (Request.QueryString["source"] != null)
                        {
                            string s = Request.QueryString["source"].ToLower().ToString();   //取出从哪个页面转来的
                            Session["user"] = txtUID.Text;
                            Response.Redirect(s); //转到用户想去的页面
                        }
                        else
                        {
                            Response.Redirect("main.aspx");    //默认转向main.aspx
                        }
                    } 
                } 
            第五步:在Web.Conofig中注册一下这个HttpModule模块
          
<httpModules>
           <add name="TestModule" type="ClassLibrary831.TestModule,ClassLibrary831"></add>
          </httpModules> 
 
接下来联系项目实例:
(1)控制器:
 1    [ HttpPost]
 2         public ActionResult LogOn(LogOnModel model, string returnUrl)
 3         {
 4             if (!ModelState.IsValid)
 5             {
 6                 return View(model);
 7             }
 8 
 9             //验证注册信息
10             //string localCode = System.Configuration.ConfigurationManager.AppSettings["LocalCode"];
11             //if (localCode == null || localCode != "98D4A31D9BC700F0B11F2679E9316814BA3DED4CF7C77EBA")//开发期间本地跳过注册程序
12             //{
13             //    if (!Auth())
14             //    {
15             //        ModelState.AddModelError("", "系统未注册,无法登录!");
16             //        return View(model);
17             //    }
18             //}
19 
20             //AccountRepository accountRp = new AccountRepository();
21             var userinfo = new NewUserRepository().GetUser(model.UserName, model.Password);
22             if (userinfo != null )
23             {
24                 string onlineName = userinfo.UserID + userinfo.UserName;
25                 string loginIp = HttpContext.Request.UserHostAddress;
26 
27                 OnlineUser nowOnlineUser = UserOnlineModule .OnlineList.Find(e => e.UserName == onlineName);
28                 if (nowOnlineUser != null )
29                 {
30                     if (nowOnlineUser.LoginIp != loginIp)
31                     {
32                         ModelState.AddModelError( "", "所登录帐号已在其他地址登录." );
33                         return View(model);
34                     }
35                 }
36                 else
37                 {
38                     nowOnlineUser = new OnlineUser ();
39                     nowOnlineUser.UserName = onlineName;
40                     nowOnlineUser.LoginTime = DateTime.Now;
41                     nowOnlineUser.LastTime = DateTime.Now;
42                     nowOnlineUser.LoginIp = HttpContext.Request.UserHostAddress;
43                     nowOnlineUser.LastActionUrl = HttpContext.Request.Url.PathAndQuery;
44                     nowOnlineUser.SessionID = HttpContext.Session.SessionID.ToUpper();
45                     nowOnlineUser.IsGuest = false;
46                     UserOnlineModule.OnlineList.Add(nowOnlineUser);
47                 }
48 
49                 string userData = userinfo.UserID + "," + userinfo.UserName + "," + userinfo.DepNO + "," + userinfo.PID;
50                 FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
51                     userData,
52                     DateTime.Now,
53                     DateTime.Now.AddMinutes(30),
54                     false,
55                     userData,
56                     FormsAuthentication.FormsCookiePath);
57 
58                 // Encrypt the ticket.
59                 string encTicket = FormsAuthentication .Encrypt(ticket);
60 
61                 var cookietemp = new HttpCookie( FormsAuthentication.FormsCookieName, encTicket);
62                 //cookietemp.Expires = DateTime.Now.AddMinutes(20); //设置cookies的过期时间
63                 // Create the cookie.
64                 Response.Cookies.Add(cookietemp);
65                 //FormsAuthentication.SetAuthCookie(userinfo.UserID + "," + userinfo.UserName + "," + empid + "," + userinfo.DepNO, false);
66                 //在后续的函数中,通过例如UserID = HttpContext.Current.User.Identity.Name.Split(',')[0];的方式获得需要的用户信息元数据
67                 //还可以通过FormsAuthenticationTicket的方式,参见http://msdn.microsoft.com/en-us/library/system.web.security.formsauthenticationticket.aspx
68                 //可以实现Cookie的加密等等,以后要实现。
69                 if (!String .IsNullOrEmpty(returnUrl)) return Redirect(returnUrl);
70                 else return RedirectToAction("Index", "Home");
71             }
72 
73             ModelState.AddModelError( "", "用户帐号信息有误,帐号或密码错误." );
74             return View(model);
75         }
(2)IHttpModule接口:
 1     public class UserOnlineModule : IHttpModule
 2     {
 3         #region IHttpModule 成员
 4 
 5         public static List< OnlineUser> OnlineList = null ;
 6         private System.Timers.Timer updateTimer;
 7         //在线用户活动超时:分钟,默认10分钟
 8         private int timeOut = 10;
 9         //设置计时器触发周期:毫秒,默认1分钟
10         private double timeInterval = 60000;
11 
12         public void Init(HttpApplication context)
13         {
14             context.AuthenticateRequest += new EventHandler (context_AuthenticateRequest);
15         }
16 
17         void context_AuthenticateRequest(object sender, EventArgs e)
18         {
19             if (OnlineList == null )
20                 OnlineList = new List <OnlineUser>();
21 
22             updateTimer = new System.Timers.Timer ();
23             updateTimer.AutoReset = true;
24             updateTimer.Elapsed += new System.Timers.ElapsedEventHandler (updateTimer_Elapsed);
25             updateTimer.Interval = timeInterval;
26             updateTimer.Start();
27         }
28 
29         void updateTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
30         {
31             updateTimer.Stop();
32             if (OnlineList.Count > 0)
33                 OnlineList.RemoveAll(p => ( DateTime.Now - p.LastTime).Minutes >= timeOut);
34             updateTimer.Interval = timeInterval;
35             updateTimer.Start();
36         }
37 
38         public void Dispose()
39         {
40 
41         }
42         #endregion
43     }
(3)记住需要在web.config文件里面注册一下这个HttpModule模块(这个很重要,我刚开始就是没弄这个,导致怎么也弄不出来)
 < httpModules>
      < add name ="OnlineList " type ="CoreLibrary.Helper.UserOnlineModule "/>
    </ httpModules>

(4)至于视图方面就很简单了:

 1 @Html.ValidationSummary(true, "Login was unsuccessful. Please correct the errors and try again.")
 2 <div data-role="fieldcontain">
 3 @using (Html.BeginForm("LogOn", "Account", FormMethod.Post, new { @class = "form login" }))
 4 {            
 5                 @Html.LabelFor(m => m.UserName)
 6                 @Html.TextBoxFor(m => m.UserName, new { required="required",placeHolder="User Name"})
 7                 @Html.ValidationMessageFor(m => m.UserName)
 8                 <br />
 9                 @Html.LabelFor(m => m.Password)
10                 @Html.PasswordFor(m => m.Password, new { required = "required", placeHolder = "Password" })
11                 @Html.ValidationMessageFor(m => m.Password)
12 
13                 <br />
14                
15            @Html.CheckBoxFor(m=>m.RememberMe)
16            @Html.LabelFor(m=>m.RememberMe)
17           <input type="submit" value="Log On" />
18   
19 }
20 </div>

好了,大致就是这样了,如果有什么问题的话就欢迎交流探讨。

posted @ 2013-09-11 20:37  真假不分  阅读(12187)  评论(1编辑  收藏  举报