您好,登录后才能下订单哦!
这篇文章给大家介绍Asp.Net MVC4中怎么验证用户登录,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。
首先在HomeController 控制器的返回函数
public ActionResult Index(){...}前面加上:
[Authorize(Roles = "admins")]
就是这样:
[Authorize(Roles = "admins")]
public ActionResult Index()
{
...
}这条语句的意思是在这加上一个权限验证,只允许用户角色是admins的用户访问
然后再web.config文件里添加:
<authentication mode="Forms"> <forms loginUrl="~/Login" timeout="2880" /> </authentication>
这些的意思是给整个网站增加用户验证,指向的登陆界面是login这个控制器
CDBTemplate.cs文件里的一个类:
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,在页面里面加上下面的代码:
@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 { })
@Html.PasswordFor(m => m.Password)
@Html.ValidationMessageFor(m => m.Password,"请输入密码!",new { })
@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 控制器中增加这么一个方法:
[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("~/");
}关于Asp.Net MVC4中怎么验证用户登录就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。