在上一期七天学会 ASP.NET MVC 中,小编为大家讲解了 MVC 的用户授权认证问题。
今天,来为大家讲解 MVC 的用户角色管理知识。
用户角色管理是开发中经常遇到的问题,针对管理员权限的登录与非管理员的登录需要做出不同的处理。那么在具体实现中,我们该如何操作呢?
下面,小编来为大家详细介绍。
一、非管理员用户登录时,需要隐藏 Add New 链接
1. 创建标识用户身份的枚举类型
右击 Model 文件夹,选择添加新项目。选择 “Code File” 选项。
输入 “UserStatus” 名,点击添加。
“Code File” 选项会创建一个 “.cs” 文件.
创 UserStatus 枚举类型,如下:
namespace WebApplication1.Models
{
public enum UserStatus
{
AuthenticatedAdmin,
AuthentucatedUser,
NonAuthenticatedUser
}
}
2. 修改业务层功能
删除 IsValidUser 函数,创建新函数 “GetUserValidity“,如下:
public UserStatus GetUserValidity(UserDetails u)
{
if (u.UserName == "Admin" && u.Password == "Admin")
{
return UserStatus.AuthenticatedAdmin;
}
else if (u.UserName == "Sukesh" && u.Password == "Sukesh")
{
return UserStatus.AuthentucatedUser;
}
else
{
return UserStatus.NonAuthenticatedUser;
}
}
3. 修改 DoLogin action 方法
打开 AuthenticationController, 修改 DoLogin action:
[HttpPost]
public ActionResult DoLogin(UserDetails u)
{
if (ModelState.IsValid)
{
EmployeeBusinessLayer bal = new EmployeeBusinessLayer();
//New Code Start
UserStatus status = bal.GetUserValidity(u);
bool IsAdmin = false;
if (status==UserStatus.AuthenticatedAdmin)
{
IsAdmin = true;
}
else if (status == UserStatus.AuthentucatedUser)
{
IsAdmin = false;
}
else
{
ModelState.AddModelError("CredentialError", "Invalid Username or Password");
return View("Login");
}
FormsAuthentication.SetAuthCookie(u.UserName, false);
Session["IsAdmin"] = IsAdmin;
return RedirectToAction("Index", "Employee");
//New Code End
}
else
{
return View("Login");
}
}
在上述代码中,已经出现 Session 变量来识别用户身份。
什么是 Session?
Session 是 Asp.Net 的特性之一,可以在 MVC 中重用,可用于暂存用户相关数据,session 变量周期是穿插于整个用户生命周期的。
4. 移除存在的 AddNew 链接
打开 “~/Views/Employee” 文件夹下 Index.cshtml View,移除 “Add New” 超链接。
5. 创建分部 View
右击“~/Views/Employee”文件夹,选择添加View,设置View名称”“AddNewLink”“,选中”Create a partial View“复选框。
6. 输入分部 View 的内容
在新创建的分部视图中输入以下内容:
7. 新建 Action 方法
打开 EmployeeController,新建Action 方法”GetAddNewLink“,如下:
public ActionResult GetAddNewLink()
{
if (Convert.ToBoolean(Session["IsAdmin"]))
{
return Partial View("AddNewLink");
}
else
{
return new EmptyResult();
}
}
8. 显示 AddNew 链接
打开 Index.html,输入以下代码:
@{
Html.RenderAction("GetAddNewLink");
}