这几天在用MVC做一个项目,用到了HttpContext.User.IsInRole() 这个方法,但是每次当我用的时候,HttpContext.User.IsInRole(“Admin”) 返回的永远是false。 在网上查了很多资料,发现都没有解决,要解决的话,也要实现一系列的扩展方法。好,废话少说,正式进入主题:

权限判断
if (HttpContext.User.Identity == null || String.IsNullOrEmpty(HttpContext.User.Identity.Name))
{
return Redirect("~/Account/LogOn?returnUrl=/service");
}
else if (HttpContext.User.IsInRole("Admin"))
{
return RedirectToAction("Index", "AdminService");
}
else
{
…….
} if (HttpContext.User.Identity == null || String.IsNullOrEmpty(HttpContext.User.Identity.Name))
 {
      return Redirect("~/Account/LogOn?returnUrl=/service");
 }
else if (HttpContext.User.IsInRole("Admin"))
  {
         return RedirectToAction("Index", "AdminService");
 }
else
{
  …….
}

上面的代码中HttpContext.User.IsInRole(“Admin”) 返回的是false。我们要返回True怎么办?

在Global.asax中添加以下方法:

/// <summary>
/// Authen right for user
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
////给登陆用户赋权限
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
if (HttpContext.Current.User != null)
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
if (HttpContext.Current.User.Identity is FormsIdentity)
{
//Get current user identitied by forms
FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
// get FormsAuthenticationTicket object
FormsAuthenticationTicket ticket = id.Ticket;
string userData = ticket.UserData;
string[] roles = userData.Split(',');
// set the new identity for current user.
HttpContext.Current.User = new GenericPrincipal(id, roles);
}
}
}
} /// <summary>
/// Authen right for user
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
        {
            if (HttpContext.Current.User != null)
            {
                if (HttpContext.Current.User.Identity.IsAuthenticated)
                {
                    if (HttpContext.Current.User.Identity is FormsIdentity)
                    {
                        //Get current user identitied by forms
                        FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
                        // get FormsAuthenticationTicket object
                        FormsAuthenticationTicket ticket = id.Ticket;
                        string userData = ticket.UserData;
                        string[] roles = userData.Split(',');
                        // set the new identity for current user.
                        HttpContext.Current.User = new GenericPrincipal(id, roles);
                    }
                }
            }
        }

添加好以后,进入你的登录页面,给当前用户授权。请看:

LogOn
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
if (ModelState.IsValid)
{
if(ValidateUser(model.UserName, model.Password)))
{
//给登陆成功用户赋于指定权限
UserInfo userInfo = GetuserInfo(model.UserName);
if (userInfo.Role =="Admin") {
role = "Admin";
}
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1,
userInfo.Alias,
DateTime.Now,
DateTime.Now.AddMinutes(30),
false,
role);
string encTicket = FormsAuthentication.Encrypt(authTicket);
this.Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName,encTicket));
// FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
&& !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
} [HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
   if (ModelState.IsValid)
   {
     if(ValidateUser(model.UserName, model.Password)))
     {
 UserInfo userInfo = GetuserInfo(model.UserName);
if (userInfo.Role =="Admin")                    {
    role = "Admin";
}
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1,
                        userInfo.Alias,
                        DateTime.Now,
                        DateTime.Now.AddMinutes(30),
                        false,
                        role);
                    string encTicket = FormsAuthentication.Encrypt(authTicket);
                    this.Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName,encTicket));                   //  FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }             // If we got this far, something failed, redisplay form
            return View(model);
        }

好了,直到这里,所有的问题,已经解决了。如果大家有其他的好的方法,可以分享, 欢迎留言指正 :)

最新文章

  1. js加解密
  2. angularJs之template指令
  3. Jade之Extends
  4. ThroughRain第二次冲刺(每天更新
  5. Ibatis学习总结4--SQL Map XML 映射文件扩展
  6. SSH使用缩写
  7. jsoup 获取指定页面的所有链接(需后续完善)
  8. sql server2008评估期已过...问题
  9. ecshop调用文章显示上一篇下一篇
  10. 使用SignalR 提高B2C商城用户体验1
  11. FireDAC
  12. Vijos 1121 马拦过河卒
  13. HTML5培训哪里靠谱
  14. java下蛇形回环矩阵的实现
  15. Django 项目创建之前的环境搭建
  16. Storm入门(四)WordCount示例
  17. Nginx下完美解决WordPress的伪静态 (wordpress 迁移后 导致 页面404)
  18. C3P0连接池温习1
  19. 四、windows下TortoiseGit的使用与操作
  20. bzoj5006: [THUWC2017 Bipartite]随机二分图

热门文章

  1. js 给url添加时间戳 解决浏览器缓存
  2. 解决dom4j加载xml文件性能慢的问题
  3. DIV可编辑后,与限制输入及光标偏移的纠葛
  4. 洛谷——P3907 圈的异或
  5. [Thu Summer Camp2016]补退选
  6. assert.notStrictEqual()详解
  7. STM32——GPIO口的八种工作模式
  8. Leetcode 188.买卖股票的最佳时机IV
  9. HDU1755
  10. 洛谷——P1151 子数整数