下面详细介绍该功能的完成方法,尾部有实例源码下载,希望可以给刚开始接触MVC的朋友做个参考.
第一步:给VS安装MVC4框架
VS2012自带MVC4框架,其他版本可以使用独立安装包进行安装,这里就不讨论了,本例使用VS2013创建,.NET4.0+MVC4
第二步:创建MVC4网站项目
选择文件-新建-项目,按下图示例创建一个空的MVC网站
第三步:配置web.config,启用Form验证.
打开根目录下的web.config,在<system.web>节点下插入一下代码,启用Form验证并指定默认登录页面
<authentication mode="Forms"> ?????<forms loginUrl="/Home/Login" timeout="2880"/></authentication>
第四步:创建所需要文件
本例需要创建以下文件:
Model文件夹下LoginModel.cs
Controllers文件夹下HomeController.cs
View下创建文件下Home,文件夹下创建文件:
Index.cshtml
Login.cshtml
Show.cshtml
Edit.cshtml
Add.cshtml
文件结构如下图所示:
第五步:填充LoginModel代码
public class LoginModel ???{ ???????[Display(Name="用户名")] ???????[Required(ErrorMessage="用户名不能为空")] ???????public string UserName { get; set; } ????????[Display(Name="密码")] ???????[Required(ErrorMessage="密码不能为空")] ???????[DataType(DataType.Password)] ???????[RegularExpression(@"^\w+$", ErrorMessage = "密码格式有误,只能是字母数字或者下划线")] ?????????public string Password { get; set; } ?????????[Display(Name="记住登陆?")] ???????public bool RememberMe { get; set; } ????????public string Login() ???????{ ???????????//该方法应从数据库中对比用户名和密码,并取得用户权限列表 ???????????//这里为了简单直接对比字符串并返回权限列表,返回NULL则说明用户名或者密码错误 ???????????//权限列表即为用,分割的权限名称 ???????????string result = null; ????????????if (this.UserName == "guest" & this.Password == "guest") ???????????????result = "Add"; ????????????if (this.UserName == "admin" & this.Password == "admin") ???????????????result = "Add,Edit"; ????????????return result; ???????} ???}
复制上面代码到类中时VS的智能感知会提示你缺少以下命名空间,添加上即可
using System.ComponentModel.DataAnnotations;
第五步:填充HomeControll代码
public class HomeController : Controller ???{ ???????// ???????// GET: /Home/ ????????public ActionResult Index() ???????{ ???????????ViewBag.Info = "该页面不含权限注解,所有人均可访问."; ???????????return View(); ???????} ???????????????[Authorize(Roles = "Edit")] //该注解表示只有包含Edit权限的用户才可以访问 ???????public ActionResult Edit() ???????{ ???????????ViewBag.Info = "该页面需要包含Edit权限的人才可访问."; ???????????return View(); ???????} ???????[Authorize(Roles = "Add")] //该注解表示只有包含Add权限的用户才可以访问 ???????public ActionResult Add() ???????{ ???????????ViewBag.Info = "该页面需要包含Add权限的人才可访问."; ???????????return View(); ???????} ???????[Authorize(Roles = "Add,Edit")] //该注解表示只有包含Add权限的用户才可以访问 ???????public ActionResult Show() ???????{ ???????????ViewBag.Info = "该页面需要包含Edit或者Add权限的人才可访问."; ???????????return View(); ???????} ???????public ActionResult Login(LoginModel model) ??????{ ??????????return View(); ??????} ???????[HttpPost] //该注解表示只接收Post数据 ??????[ValidateAntiForgeryToken]//该注解可以防止跨站攻击 ??????[ActionName("Login")]//该注解可以更改路由中Action名称 ??????public ActionResult LoginCheck(LoginModel model) ??????{ ??????????if (!ModelState.IsValid) ??????????{ ??????????????//用户输入服务端验证,此处处理验证不通过的提示代码 本例略过 ???????????????????????????return View(); ??????????} ???????????string result = model.Login(); ???????????if (result == null) ??????????{ ??????????????//用户名或者密码不正确的提示代码 本例略过 ??????????????return View(); ??????????} ??????????else ??????????{ ??????????????//用户登陆核心代码 ??????????????FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket( ???????????????????1, ???????????????????model.UserName, ???????????????????DateTime.Now, ???????????????????DateTime.Now.AddHours(240),//记住密码的时间 ???????????????????model.RememberMe,//是否保存cookie 记住密码 ???????????????????result //获取的用户权限列表 用逗号分割的字符串 ???????????????????); ??????????????string encryptedTickt = FormsAuthentication.Encrypt(authTicket); ??????????????HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTickt); ??????????????Response.Cookies.Add(authCookie); ???????????????Response.Redirect("/Home", true); ??????????????ActionResult empty = new EmptyResult(); ??????????????return empty; ??????????} ??????????return View(); ??????}
复制以上代码,会提示添加以下命名空间:
using ChengChenXu.MVC4_Login_Demo.Models; //项目Model命名空间using System.Web.Security;
第六步:填充View代码,下面代码仅展示<Body>标签内部的内容,页头没有展示(源码中完全).
Index.cshtml
<h1>@ViewBag.Info</h1><br /> ???????<a href="/home/login">登陆</a><br /> ???????<p>以下链接 登陆后才可以访问 未登陆时如果点击则会跳转到登陆页</p> ???????<a href="/home/add">添加页面</a><br /> ???????<a href="/home/edit">编辑页面</a><br /> ???????<a href="/home/show">查看页面</a><br />
Add.cshtml Edit.cshtml Show.cshtml 三个文件代码一致
<h1>@ViewBag.Info</h1> ???????<a href="/home">返回</a><br />
Login.cshtml 该文件首先要在顶部添加一行代码,表示是一个强类型View
@model ChengChenXu.MVC4_Login_Demo.Models.LoginModel
页面代码:
@using (Html.BeginForm()) ???????????{ ???????????????@Html.AntiForgeryToken() ????????????????????????????@Html.LabelFor(model=>model.UserName) ???????????????@Html.TextBoxFor(model => model.UserName) ???????????????<br /> ????????????????@Html.LabelFor(model=>model.Password) ???????????????@Html.PasswordFor(model => model.Password) ???????????????<br /> ????????????????????????????@Html.LabelFor(Model=>Model.RememberMe) ???????????????@Html.CheckBoxFor(model=>model.RememberMe) ???????????????<br /> ????????????????????????????<input type="submit" class="submit" tabindex="3" value="登录" /> ????????????}
第七步:修改根目录下Global.asax的代码,添加权限处理代码,把下面两个方法复制添加到Global文件即可
public MvcApplication() ???????{ ???????????AuthorizeRequest += new EventHandler(MvcApplication_AuthorizeRequest); ???????} ????????void MvcApplication_AuthorizeRequest(object sender, EventArgs e) ???????{ ???????????var id = Context.User.Identity as FormsIdentity; ???????????if (id != null && id.IsAuthenticated) ???????????{ ???????????????var roles = id.Ticket.UserData.Split(‘,‘); ???????????????Context.User = new GenericPrincipal(id, roles); ???????????} ???????}
复制好后会提示缺少以下命名空间:
using System.Web.Security;using System.Security.Principal;
完成好之后全部实例就完成了,运行以下试试吧.
主页为/Home 无需权限
登录页为/Home/Login 无需权限
添加页为/Home/Add 需要Add权限
展示页为/Home/Show 需要Edit或者Add权限
编辑页为/Home/Edit 需要Edit权限
内置了两个账号
账号 密码 权限
guest guest "add"
admin admin "add,edit"
运行结果:
如果直接访问除了Home和Login页面之外的页面(需要权限的页面) 则会跳转到Login页面
guest账号可以访问Add Show页面
admin账号可以访问Add Edit Show页面
锦上添花:
1 自动跳转到登录页的时候URL会有一个ReturnUrl参数记录跳转前的页面,可以捕捉该页面登录后跳回
2 MVC支持客户端验证,需要js文件支持,这样客户端就不再需要写js代码进行输入验证了.本例不再展示了,请自行搜索.
本博文转自我的博客:http://chengchenxu.com/Article/show/14/
源码下载:http://chengchenxu.com/ueditor/net/upload/file/20180305/6365584952537468509926479.rar