我第一次使用会员和角色提供程序登录我的登录页面。我的会员资格很好但我无法在登录页面上使用角色提供程序。 我有一个名为MyAccount控制器的控制器。此控制器将验证用户成员资格,验证后将根据用户角色重定向到Home控制器。 这是
MyAccount控制器:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(Login l, string returnUrl = "")
{if (ModelState.IsValid)
{
var isValidUser = Membership.ValidateUser(l.UserName, l.Password);
if (isValidUser)
{
FormsAuthentication.SetAuthCookie(l.UserName, l.RememberMe);
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else If(*"USER ROLE AS ADMIN"*)
{
RedirectToAction("AdminIndex","Home");
}
else
{
RedirectToAction("ClientIndex","Home");
}
}
}
ViewBag.ErrorMassage = "Wrong Id or Password";
ModelState.Remove("Password");
return View();
}
并且
家庭控制器:
[Authorize (Roles= "Admin")]
public ActionResult AdminIndex()
{
return View();
}
[Authorize (Roles = "Client")]
public ActionResult ClientIndex()
{
return View();
}
我不确定我应该在MyAccount控制器或家庭控制器中检查用户角色?
RoleProvider:
public override string[] GetRolesForUser(string username)
{
if (!HttpContext.Current.User.Identity.IsAuthenticated)
{
return null;
}
//check cache
var cacheKey = string.Format("{0}_role", username);
if (HttpRuntime.Cache[cacheKey] != null)
{
return (string[])HttpRuntime.Cache[cacheKey];
}
string[] roles = new string[] { };
roles = gateway.GetUserRole(username);
{
if (roles.Any())
{
HttpRuntime.Cache.Insert(cacheKey, roles, null, DateTime.Now.AddMinutes(_cacheTimeoutInMinute), Cache.NoSlidingExpiration);
}
}
return roles;
}
public override bool IsUserInRole(string username, string roleName)
{
var userRoles = GetRolesForUser(username);
return userRoles.Contains(roleName);
}
如何将此RoleProvider用于我的控制器并将其重定向到管理员或客户端操作?
答案 0 :(得分:0)
在web.config
注册您的自定义角色提供程序:
<roleManager defaultProvider="DefaultRoleProvider">
<providers>
<add name="DefaultRoleProvider" type="MyNamespace.MyRoleProvider, MyAssembly" />
</providers>
</roleManager>
在Login
控制器上更新MyAccount
操作方法:
if (Roles.IsUserInRole("Admin"))