2012-02-22 68 views
0

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

是否可以扩展授权属性来检查特定用户在哪个位置?例如[Authorize(Roles =“Administrator”,Location =“ICT”)]?

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

在此先感谢。

回答

3

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

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

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")] 
+0

嗨达林,我在哪里上这门课? – 2012-02-22 09:27:09

+0

@StewieFG,无论你在哪里。你的ASP.NET MVC应用程序是一个很好的地方。你可以创建一个子文件夹来组织你的自定义授权属性或其他。 – 2012-02-22 09:29:08

+0

谢谢达林 – 2012-02-22 09:32:20