我正在尝试编写一个自定义属性,可以验证用户是否有权使用某个控制器。在Stackoverflow上找到此链接ASP.NET MVC 4 Custom Authorize Attribute with Permission Codes (without roles)。我的问题是我无法使用User.Identity.GetUserId
来编写任何类型的查询。它抛出了"Error 1 The name 'User' does not exist in the current context"
的错误。添加using Microsoft.AspNet.Identity;
也没有帮助。我基本上想检查某些AccessLevel是否对登录用户有效。为此,我计划进入数据库并查询登录用户。我正在学习这个,所以请告知我这样做是完全错误的。
以下是我开始使用的代码。
感谢。
public class UserAuthorizeAttributes : AuthorizeAttribute
{
public string AccessLevel { get; set; }
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
// Check if valid credentials are there for selected User.Identity.GetUserId() in database
{ return true ; }
else
{ return false; }
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
filterContext.Result = new RedirectResult("/TimeShare/Account/LogOn");
base.HandleUnauthorizedRequest(filterContext);
}
}
所以我打算在控制器中使用如下
[UserAuthorizeAttributes(AccessLevel ="UserAdmin")]
public class XXXXController : Controller {
}