处于安全性考虑,MVC可以完成授权认证,授权认证的方式如下:
1、配置Config文件,设置登录页面:
<authentication mode="Forms"> <forms loginUrl="~/Authentication/Login" timeout="2880" /> <!--<forms cookieless="UseUri" loginUrl="~/Authentication/Login"></forms>--> </authentication>
2、Action添加授权认证属性Authorize:
[Authorize] public ActionResult Index() { EmployeeBusinessLayer empBal = new EmployeeBusinessLayer(); List<Employee> employees=empBal.GetEmployees(); List<EmployeeViewModel> empviewModels = new List<EmployeeViewModel>(); foreach (Employee emtp in employees) { EmployeeViewModel vmEmp = new EmployeeViewModel(); vmEmp.EmployeeName = emtp.FirstName + " " + emtp.LastName; vmEmp.Salary = emtp.Salary.ToString("C"); if (emtp.Salary > 15000) { vmEmp.SalaryColor = "yellow"; } else { vmEmp.SalaryColor = "green"; } empviewModels.Add(vmEmp); } EmployeeListViewModel currlistmodel = new EmployeeListViewModel(); currlistmodel.UserName = User.Identity.Name; currlistmodel.Employees = empviewModels; return View(currlistmodel); }
备注:显示当前用户信息,User.Identity.Name获取
3、设置授权认证。
FormsAuthentication.SetAuthCookie(udemail.UserName, false);//表示通过身份认证
FormsAuthentication.SignOut();//表示注销身份认证
Login页面代码如下:
@using MyMVC3Demo.Models; @model UserDetails @{ Layout = null; } <!DOCTYPE html> <html> <head> <title>Login</title> <script src="../../Scripts/jquery-1.8.0.min.js" type="text/javascript"></script> <script src="../../Scripts/jquery.validate.js" type="text/javascript"></script> <script src="../../Scripts/jquery.validate.unobtrusive.js" type="text/javascript"></script> </head> <body> <div> @Html.ValidationMessage("CredentialError", new { style = "color:red;" }) @using(Html.BeginForm("DoLogin","Authentication",FormMethod.Post)) { @Html.LabelFor(c=>c.UserName) @Html.TextBoxFor(x=>x.UserName) @Html.ValidationMessageFor(x => x.UserName) <br /> @Html.LabelFor(c => c.Password) @Html.PasswordFor(c => c.Password) <br /> <input type="submit" name="BtnSubmit" value="Login" /> } </div> </body> </html>
备注1: @Html.TextBoxFor(x=>x.UserName)转换为HTML代码<input id="UserName" name="UserName" type="text" value="" />
2:@using (Html.BeginForm("DoLogin", "Authentication", FormMethod.Post)){ }
转换为HTML代码<form action="/Authentication/DoLogin" method="post"> </form>
Control代码如下:
public ActionResult Login() { return View(); } public ActionResult Logout() { FormsAuthentication.SignOut(); return RedirectToAction("Login"); } [HttpPost] public ActionResult DoLogin(UserDetails udemail) { if (ModelState.IsValid) { EmployeeBusinessLayer bll = new EmployeeBusinessLayer(); if (bll.IsValidUser(udemail)) { FormsAuthentication.SetAuthCookie(udemail.UserName, false); return RedirectToAction("Index", "Employee"); } else { ModelState.AddModelError("CredentialError", "Invalid Username or Password"); return View("Login"); } } else { return View("Login"); } }
ModelState.IsValid是对Model类型的校验;
ModelState.AddModelError(),自定义错误类型,便于前台显示;
@Html.ValidationMessage("CredentialError", new { style = "color:red;" })
补充:
用客户端显示错误信息
1、选择“Manage Nuget packages”,点击在线查找”jQuery Unobtrusive“,安装”Microsoft jQuery Unobtrusive Valiadtion“
2、引用一下JS
- jQuery-Someversion.js
- jQuery.valiadte.js
- jquery.validate.unobtrusive
3、利用Unobtrusive展示错误消息的主要原因在HtmlHelp类能够将
@Html.TextBoxFor(x=>x.UserName)
@Html.ValidationMessageFor(x=>x.UserName)
转换成
<input data-val="true" data-val-length="UserName length should be between 2 and 7" data-val-length-max="7" data-val-length-min="2" id="UserName" name="UserName" type="text" value="" />
<span class="field-validation-error" data-valmsg-for="UserName" data-valmsg-replace="true"> </span>
而data-val-length又是Unbtrusive内置的数据属性,所以能够利用前端拦截错误信息