【发布时间】:2016-02-02 06:19:02
【问题描述】:
您好,我正在尝试使用自定义授权属性,但 base.AuthorizeCore 总是返回 false。我不知道我在哪里做错了。你能告诉我问题出在哪里吗?我的 AuthorizeAttribute:
public class AuthorizeUserAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var isAuthorized = base.AuthorizeCore(httpContext);
if (!isAuthorized)
{
return false;
}
string roles = string.Join("", httpContext.Session["UserRole"]);
// string roles = string.Join("", HttpContext.Current.Session["UserRole"]);
if (Roles.Contains(roles))
{
return true;
}
else
{
return false;
}
}
我的登录方法:
public ActionResult LogIn()
{
var model = new UserModel();
return View(model);
}
[HttpPost]
public ActionResult LogIn(UserModel model)
{
if (!ModelState.IsValid)
{
return View("LogIn", model);
}
else
{
var usermodelDB = _UserAccountService.GetUser(model.Password);
if (model.userName == usermodelDB.userName && model.Password==usermodelDB.Password)
{
model.userRole = usermodelDB.userRole;
FormsAuthentication.SetAuthCookie(model.userRole, true);
System.Web.HttpContext.Current.Session["UserRole"] = usermodelDB.userRole;
var ia =System.Web.HttpContext.Current.User.Identity.IsAuthenticated;
}
return View("LogIn", model);
}
}
以及访问受限的方法:
[AuthorizeUser(Roles="User")]
public ActionResult Index(int page=0)
{
return View();
}
【问题讨论】:
标签: c# asp.net-mvc authorization