zoukankan      html  css  js  c++  java
  • Authorize 示例

    using System;   
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    namespace AuthTest.Models
    {
    public class MyAuthAttribute : AuthorizeAttribute
    {
    // 只需重载此方法,模拟自定义的角色授权机制
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
    string currentRole = GetRole(httpContext.User.Identity.Name);
    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);
    return View();
    }

    // 验证我们自定义的AuthorizeAttribute是否起作用,
    // 此Action只能由角色为“God”的用户访问
    [MyAuth(Roles="God")]
    public ActionResult About()
    {
    return View();
    }
    }
    }



  • 相关阅读:
    MySQL之ORM
    MySQL之索引补充
    MySQL存储过程
    c primer plus 7编程练习
    c语言中统计单词数目程序
    c语言统计输入字符数及行数
    c语言中getchar()、putchar()函数例子
    c primer plus 6编程练习
    c语言 %c 一次输出多个字符 (特殊程序)
    c语言 复合赋值运算符的优先级低于算术运算符
  • 原文地址:https://www.cnblogs.com/yannis/p/2281762.html
Copyright © 2011-2022 走看看