【问题标题】:MVC3 Extra role attributeMVC3 额外角色属性
【发布时间】:2012-03-12 14:47:24
【问题描述】:

我正在创建一个网站,管理员可以在其中添加教师和学生,管理员应该能够指定教师在特定位置时可以执行的操作。

是否可以扩展 Authorize 属性以检查特定用户所在的位置?例如 [Authorize(Roles = "Administrator", Location="ICT")] ?

如果是这样,我该如何扩展它?

提前致谢。

【问题讨论】:

    标签: asp.net asp.net-mvc-3


    【解决方案1】:

    如果是这样,我该如何扩展它?

    通过编写自定义授权属性:

    public class MyAuthorizeAttribute : AuthorizeAttribute
    {
        public string Location { get; set; }
    
        protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
        {
            var result = base.AuthorizeCore(httpContext);
            if (!result)
            {
                return false;
            }
    
            // At this stage we know that the currently logged in user 
            // is authorized. Now you could use the Location property
            // to perform additional custom authorization checks and
            // return true or false from here
    
            string user = httpContext.User.Identity.Name;
    
            ...
        }
    }
    

    然后:

    [MyAuthorize(Roles = "Administrator", Location = "ICT")]
    

    【讨论】:

    • 嗨达林,我在哪里安排这门课?
    • @StewieFG,随心所欲。您的 ASP.NET MVC 应用程序是一个好地方。您可以创建一个子文件夹来组织您的自定义授权属性或其他任何内容。
    • 谢谢,正是我需要的!
    【解决方案2】:

    您可以创建自己的自定义授权属性。 在此处观看视频asp-net-mvc3-custom-membership-authorizeattribute-tutorial

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-17
      • 1970-01-01
      • 1970-01-01
      • 2020-06-07
      • 2015-02-04
      • 1970-01-01
      • 1970-01-01
      • 2020-09-09
      相关资源
      最近更新 更多