AuthorizeAttribute示例
示例
2023-09-14 08:59:23 时间
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace AuthTest.Models { public class MyAuthAttribute : AuthorizeAttribute { // 只需重载此方法,模拟自定义的角色授权机制,推荐通过Idetity获取用户信息, 当然也可以通过Session获取,如果通过Session获取需要在验证的时候吧用户信息写入Session protected override bool AuthorizeCore(HttpContextBase httpContext) { string currentRole = GetRole(httpContext.User.Identity.Name); //string currentRole = GetRole(Session["user"].ToString()); 通过Session获取 if(Roles.Contains(currentRole ) ) return true; return base.AuthorizeCore(httpContext); } // 返回用户对应的角色, 在实际中, 可以从SQL数据库中读取用户的角色信息 private string GetRole(string name) { switch(name) { case "aaa": return "User"; case "bbb": return "Admin"; case "ccc": return "God"; default: return "Fool"; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Security; using AuthTest.Models; namespace AuthTest.Controllers { [HandleError] public class HomeController : Controller { public ActionResult Index() { ViewData["Message"] = "欢迎使用 ASP.NET MVC!"; // 模拟用户成功登录 FormsAuthentication.SetAuthCookie("aaa", false); //Session["user"]="aaa" 把用户信息写入Session return View(); } // 验证我们自定义的AuthorizeAttribute是否起作用, // 此Action只能由角色为“God”的用户访问 [MyAuth(Roles="God")] public ActionResult About() { return View(); } } }
相关文章
- 国网B接口资源上报(Push_Resourse)接口描述和消息示例
- 【Android 内存优化】自定义组件长图组件 ( 长图滚动区域解码 | 手势识别 GestureDetector | 滑动计算类 Scroller | 代码示例 )
- 【运筹学】分支定界法 ( 分支定界法相关概念 | 分支定界法求解整数规划步骤 | 分支定界理论分析 | 分支过程示例 )
- 【CSS】清除浮动 ④ ( 清除浮动 - 使用双伪元素清除浮动 | 代码示例 )
- SqlServer实现类似Oracle的before触发器示例
- 如何使用RPM命令(示例)
- js导出table到excel同时兼容FF和IE示例
- .NET命令行解析器示例程序(命令行选项功能)
- js上下左右键控制焦点(示例代码)
- 使用python绘制人人网好友关系图示例
- asp.net页面中时间格式化的示例
- c语言实现冒泡排序、希尔排序等多种算法示例
- js跨域访问示例(客户端/服务端)
- PHPUnit安装及使用示例