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>

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

ASP.NET MVC 用户登录Login的更多相关文章

  1. ASP.NET MVC用户登录(Memcache存储用户登录信息)

    一.多站点共享用户信息解决方案: 采用分布式缓存Memcache模拟Session进行用户信息信息共享 1.视图部分

  2. C# MVC 用户登录状态判断 【C#】list 去重(转载) js 日期格式转换(转载) C#日期转换(转载) Nullable<System.DateTime>日期格式转换 (转载) Asp.Net MVC中Action跳转(转载)

    C# MVC 用户登录状态判断   来源:https://www.cnblogs.com/cherryzhou/p/4978342.html 在Filters文件夹下添加一个类Authenticati ...

  3. ASP.NET MVC 用户权限-1

    MVC框架的开发网站的利器,MVC框架也开始越来越流行了.对于.NET ,微软也发布了MVC框架,做网站通常要涉及到用户的权限管理,对于.NET MVC 框架的用户权限管理又应该怎样设置呢?下面通过示 ...

  4. asp.net限制用户登录错误次数

    很经常在登录一个网站的时候看到,如果你登录的时候输入的账号密码错误超过三次就被锁定,然后等一段时间才能继续登录,最最经常使用的就是银行系统啦~~ 该功能处理流程如下: string uid = Req ...

  5. asp.net MVC 通用登录验证模块

    用法: 还是希望读者把源码看懂,即可运用自如.重点是,为什么有个UserType!!! 登录用户信息: namespace MVCCommonAuth { [Serializable] public ...

  6. C# MVC 用户登录状态判断

    来源:https://www.cnblogs.com/cherryzhou/p/4978342.html 在Filters文件夹下添加一个类AuthenticationAttribute ,代码如下: ...

  7. Asp.Net MVC 自定义登录过滤器

    1.新建类BaseController用于统一所有控制器继承扩展,方便扩展登录等过滤器.示例如下: using CloudWave.JustBeHere.JBH_H5.Controllers.Attr ...

  8. MVC用户登录方法(lamda表达式)

        public bool ValidateUser(account model) { using (assertEntities db = new assertEntities()) { acc ...

  9. Easyui + asp.net MVC 系列教程 完成登录

    Easyui + asp.net MVC 系列教程 第09-17 节 完成登录 高清录制 前面八节 在这里 Easyui + asp.net mvc + sqlite 开发教程(录屏)适合入门 在接下 ...

随机推荐

  1. 关于JavaScript中计算精度丢失的问题

    摘要: 由于计算机是用二进制来存储和处理数字,不能精确表示浮点数,而JavaScript中没有相应的封装类来处理浮点数运算,直接计算会导致运算精度丢失. 为了避免产生精度差异,把需要计算的数字升级(乘 ...

  2. C# WinForm开发系列 - WebBrowser

    原文:C# WinForm开发系列 - WebBrowser 介绍Vs 2005中带的WebBrowser控件使用以及一些疑难问题的解决方法, 如如何正确显示中文, 屏蔽右键菜单, 设置代理等; 收集 ...

  3. TCP连接状态

    TCP 连接状态按 TCP 协议的标准表示法, TCP 可具有如下几种状态,为讨论方便,如下讨论中区分服务端和客户端,实际软件处理上对二者一视同仁. CLOSED关闭状态.在两个通信端使用“三路握手” ...

  4. IOS数组排序等

    一.UITextField的代理方法 #pragma mark 当文本框开始编辑的时候调用---开始聚焦 - (void)textFieldDidBeginEditing:(UITextField * ...

  5. POJ 1035 代码+具体的目光

    Spell checker Time Limit: 2000MS Memory Limit: 65536K Total Submissions: 19319 Accepted: 7060 Descri ...

  6. ASP.NET 依赖注入。

    ASP.NET 依赖注入. http://www.it165.net/pro/html/201407/17685.html 我在网上看到了这篇文章,这边文章主要说的方法就是通过读取配置文件来解决依赖注 ...

  7. android KK版本号,如何更改蓝牙设备类型

    mediatek/external/bluetooth/bt_cust/bt_cust_table.h   {         .name = "ClassOfDevice",   ...

  8. javascript2

    代码变化一:<script> function abs(){ var x; if(x>0){ return x; } else{ return -x; } } console.log ...

  9. js对象字面量

    在编程语言中,字面量是一种表示值的记法.例如,"Hello, World!" 在许多语言中都表示一个字符串字面量(string literal ),JavaScript也不例外.以 ...

  10. WeChatAPI 开源系统架构详解

    WeChatAPI 开源系统架构详解 如果使用WeChatAPI,它扮演着什么样的角色? 从图中我们可以看到主要分为3个部分: 1.业务系统 2.WeChatAPI: WeChatWebAPI,主要是 ...