[Asp.Net MVC4]验证用户登录实现 .

最近我们要做一个仿sina的微博,碰巧的是我最近在学习mvc,就想用mvc技术实现这个项目。

既然是微博,那不用想也应该知道肯定要有用户登陆,但是和常规的asp.net登陆又不一样,以下是我一下午+一晚上的研究成果~~~

首先,建好数据库以及表,这就不用说了吧。

下面说一下主要的结构

控制器:

HomeController 这是主页的控制器

LoginController 这是登陆的控制器

类:

CDBTemplate.cs 这是数据库数据对应的类,里边描述的是数据库的结构

我是分割线\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

首先在HomeController 控制器的返回函数

  1. public ActionResult Index(){...}  
public ActionResult Index(){...}

前面加上:

  1. [Authorize(Roles = "admins")]  
[Authorize(Roles = "admins")]

就是这样:

  1. [Authorize(Roles = "admins")]  
  2. public ActionResult Index()  
  3. {  
  4.     ...  
  5. }  
[Authorize(Roles = "admins")]
public ActionResult Index()
{
    ...
}

这条语句的意思是在这加上一个权限验证,只允许用户角色是admins的用户访问


然后再web.config文件里添加:

  1. <authentication mode="Forms">  
  2.       <forms loginUrl="~/Login" timeout="2880" />  
  3. </authentication>  
<authentication mode="Forms">
      <forms loginUrl="~/Login" timeout="2880" />
</authentication>

这些的意思是给整个网站增加用户验证,指向的登陆界面是login这个控制器


CDBTemplate.cs文件里的一个类:

  1. public class LogOnModel  
  2.     {  
  3.         [Required]  
  4.         [Display(Name = "用户名")]  
  5.         public string UserName { getset; }  
  6.   
  7.   
  8.         [Required]  
  9.         [DataType(DataType.Password)]  
  10.         [Display(Name = "密码")]  
  11.         public string Password { getset; }  
  12.   
  13.   
  14.         [Display(Name = "下次自动登陆")]  
  15.         public bool RememberMe { getset; }  
  16.     }  
public class LogOnModel
    {
        [Required]
        [Display(Name = "用户名")]
        public string UserName { get; set; }


        [Required]
        [DataType(DataType.Password)]
        [Display(Name = "密码")]
        public string Password { get; set; }


        [Display(Name = "下次自动登陆")]
        public bool RememberMe { get; set; }
    }

然后为LoginController 控制器的默认返回函数增加一个视图Index.cshtml,在页面里面加上下面的代码:

  1. @model Weibo.Models.LogOnModel //LogOnModel 是CDBTemplate.cs文件里的一个类   
  2. @using (Html.BeginForm("Login","Login",FormMethod.Post)) {  
  3.     @Html.TextBoxFor(m => m.UserName)  
  4.                 @Html.ValidationMessageFor(m => m.UserName, "请输入用户名!"new {style="color: #f00" })  
  5. @Html.PasswordFor(m => m.Password)  
  6.                 @Html.ValidationMessageFor(m => m.Password,"请输入密码!",new {style="color: #f00" })  
  7. @Html.CheckBoxFor(m => m.RememberMe)  
  8.                 @Html.LabelFor(m => m.RememberMe)  
  9. @Html.ActionLink("忘记密码""forgotpwd"nullnew {@class="rt",target="_blank" })  
  10. <input type="submit" value="登陆微博" />  
  11. }  
@model Weibo.Models.LogOnModel //LogOnModel 是CDBTemplate.cs文件里的一个类
@using (Html.BeginForm("Login","Login",FormMethod.Post)) {
	@Html.TextBoxFor(m => m.UserName)
                @Html.ValidationMessageFor(m => m.UserName, "请输入用户名!", new {style="color: #f00" })
@Html.PasswordFor(m => m.Password)
                @Html.ValidationMessageFor(m => m.Password,"请输入密码!",new {style="color: #f00" })
@Html.CheckBoxFor(m => m.RememberMe)
                @Html.LabelFor(m => m.RememberMe)
@Html.ActionLink("忘记密码", "forgotpwd", null, new {@class="rt",target="_blank" })
<input type="submit" value="登陆微博" />
}
在上面的代码里Html.BeginForm("Login","Login",FormMethod.Post)方法的第一个参数的意思是指定要调用的控制器的方法的名字,第二个参数的意思是控制器的名字,第三个参数的意思是用什么方法把表单提交给服务器,这里我们为了安全,选择用post方式提交。


然后在LoginController 控制器中增加这么一个方法:

  1. [HttpPost, ActionName("Login")]  
  2.         public void Login(FormCollection collection)  
  3.         {  
  4.             object obj = SqlHelper.ExecuteScalar("select UserId from CDBUsers where UserName=@uname and Password=@pwd",  
  5.                  new SqlParameter("@uname", collection[0]),  
  6.                  new SqlParameter("@pwd", Weibo.Models.Myencrypt.myencrypt(collection[1])));  
  7.   
  8.   
  9.             if (obj != null)  
  10.             {  
  11.                 FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(  
  12.                     1,  
  13.                     collection[0],  
  14.                     DateTime.Now,  
  15.                     DateTime.Now.AddMinutes(30),  
  16.                     false,  
  17.                     "admins"  
  18.                     );  
  19.                 string encryptedTicket = FormsAuthentication.Encrypt(authTicket);  
  20.                 System.Web.HttpCookie authCookie = new System.Web.HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);  
  21.                 System.Web.HttpContext.Current.Response.Cookies.Add(authCookie);  
  22.             }  
  23.   
  24.   
  25.             Response.Redirect("~/");  
  26.         }  
[HttpPost, ActionName("Login")]
        public void Login(FormCollection collection)
        {
            object obj = SqlHelper.ExecuteScalar("select UserId from CDBUsers where UserName=@uname and Password=@pwd",
                 new SqlParameter("@uname", collection[0]),
                 new SqlParameter("@pwd", Weibo.Models.Myencrypt.myencrypt(collection[1])));


            if (obj != null)
            {
                FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
                    1,
                    collection[0],
                    DateTime.Now,
                    DateTime.Now.AddMinutes(30),
                    false,
                    "admins"
                    );
                string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
                System.Web.HttpCookie authCookie = new System.Web.HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
                System.Web.HttpContext.Current.Response.Cookies.Add(authCookie);
            }


            Response.Redirect("~/");
        }

好了,搞定了~~~~ 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值