【发布时间】:2012-03-12 14:47:24
【问题描述】:
我正在创建一个网站,管理员可以在其中添加教师和学生,管理员应该能够指定教师在特定位置时可以执行的操作。
是否可以扩展 Authorize 属性以检查特定用户所在的位置?例如 [Authorize(Roles = "Administrator", Location="ICT")] ?
如果是这样,我该如何扩展它?
提前致谢。
【问题讨论】:
标签: asp.net asp.net-mvc-3
我正在创建一个网站,管理员可以在其中添加教师和学生,管理员应该能够指定教师在特定位置时可以执行的操作。
是否可以扩展 Authorize 属性以检查特定用户所在的位置?例如 [Authorize(Roles = "Administrator", Location="ICT")] ?
如果是这样,我该如何扩展它?
提前致谢。
【问题讨论】:
标签: asp.net asp.net-mvc-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")]
【讨论】:
您可以创建自己的自定义授权属性。 在此处观看视频asp-net-mvc3-custom-membership-authorizeattribute-tutorial
【讨论】: