这几天在用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);
        }

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

MVC 用户权限HttpContext.User.IsInRole()的更多相关文章

  1. ASP.NET MVC 用户权限-1

    MVC框架的开发网站的利器,MVC框架也开始越来越流行了.对于.NET ,微软也发布了MVC框架,做网站通常要涉及到用户的权限管理,对于.NET MVC 框架的用户权限管理又应该怎样设置呢?下面通过示 ...

  2. asp.net core根据用户权限控制页面元素的显示

    asp.net core根据用户权限控制页面元素的显示 Intro 在 web 应用中我们经常需要根据用户的不同允许用户访问不同的资源,显示不同的内容,之前做了一个 AccessControlHelp ...

  3. MVC中权限的知识点及具体实现代码

    一:知识点部分 权限是做网页经常要涉及到的一个知识点,在使用MVC做权限设计时需要先了解以下知识: MVC中Url的执行是按照Controller->Action->View页面,但是我们 ...

  4. 2_MVC+EF+Autofac(dbfirst)轻型项目框架_用户权限验证

    前言 接上面两篇 0_MVC+EF+Autofac(dbfirst)轻型项目框架_基本框架 与 1_MVC+EF+Autofac(dbfirst)轻型项目框架_core层(以登陆为例) .在第一篇中介 ...

  5. asp.net mvc的权限管理设计

    现在集中展示用户-角色-权限管理的功能,因此,所有数据表一律简化处理.   1 后台管理效果 (1)角色管理 (2)权限管理   2 数据库设计(MSSQL) (1)用户表dbo.Users 项 类型 ...

  6. Asp.Net Core 项目实战之权限管理系统(7) 组织机构、角色、用户权限

    0 Asp.Net Core 项目实战之权限管理系统(0) 无中生有 1 Asp.Net Core 项目实战之权限管理系统(1) 使用AdminLTE搭建前端 2 Asp.Net Core 项目实战之 ...

  7. 从零开始学 Java - Spring AOP 实现用户权限验证

    每个项目都会有权限管理系统 无论你是一个简单的企业站,还是一个复杂到爆的平台级项目,都会涉及到用户登录.权限管理这些必不可少的业务逻辑.有人说,企业站需要什么权限管理阿?那行吧,你那可能叫静态页面,就 ...

  8. ASP.NET MVC 用户登录Login

    ASP.NET MVC 用户登录Login一.先来看个框架例子:(这个是网上收集到的)  第一步:创建一个类库ClassLibrary831.            第二步:编写一个类实现IHttpM ...

  9. C# MVC 用户登录状态判断 【C#】list 去重(转载) js 日期格式转换(转载) C#日期转换(转载) Nullable<System.DateTime>日期格式转换 (转载) Asp.Net MVC中Action跳转(转载)

    C# MVC 用户登录状态判断   来源:https://www.cnblogs.com/cherryzhou/p/4978342.html 在Filters文件夹下添加一个类Authenticati ...

随机推荐

  1. must have same number of columns as the referenced primary key

    在使用Hibernate实现多对多的测试过程中遇到了这个问题 解决的方法: 将黄色字段的内容添加进去 <set name="customerSet" table=" ...

  2. CSU 2018年12月月赛 D 2216 : Words Transformation

    Description There are n words, you have to turn them into plural form. If a singular noun ends with ...

  3. mysql多表合并为一张表

    有人提出要将4张表合并成一张.数据量比较大,有4千万条数据.有很多重复数据,需要对某一列进行去重. 数据量太大的话,可以看我另外一篇:http://www.cnblogs.com/magmell/p/ ...

  4. Spider-scrapy 中的 xpath 语法与调试

    把setting中的机器人过滤设为False ROBOTSTXT_OBEY = False 1 语法 artcile 选取所有子节点 /article 选取根元素 artile article/a 选 ...

  5. 集训第五周 动态规划 B题LIS

      Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u Submit Status Des ...

  6. cogs1752[boi2007]mokia 摩基亚 (cdq分治)

    [题目描述] 摩尔瓦多的移动电话公司摩基亚(Mokia)设计出了一种新的用户定位系统.和其他的定位系统一样,它能够迅速回答任何形如“用户C的位置在哪?”的问题,精确到毫米.但其真正高科技之处在于,它能 ...

  7. 本地==〉Github(push)

    [概述] Git中的项目是本地的,为了可以协同工作.需要将项目推送到GitHub服务器上. [步骤] 1) 第一步:创建项目 2) 第二步:在github上创建一个同名的空项目 ①选择Your rep ...

  8. jquery给span赋值

    span是最简单的容器,可以当作一个形式标签,其取值赋值方法有别于一般的页面元素. //赋值 $("#spanid").html(value) //取值 $("#span ...

  9. 创建Javaweb项目及MyEclipse视图的配置

    在myEclipse里--右键new--Web Project 视图的配置--Window--Show View-Other在里面输入要找的视图例如(servers)或者直接 Window--rese ...

  10. bzoj 2588 Spoj 10628. Count on a tree (可持久化线段树)

    Spoj 10628. Count on a tree Time Limit: 12 Sec  Memory Limit: 128 MBSubmit: 7669  Solved: 1894[Submi ...