base.AuthorizeCore(httpContext) 始终为 false - 如何找到原因
base.AuthorizeCore(httpContext) is allways false - how to find the reason
您好,我正在尝试使用自定义授权属性,但 base.AuthorizeCore 总是 return 错误。我不知道我在哪里做错了。你能告诉我问题出在哪里吗?我的授权属性:
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();
}
很可能用户不在该角色中。 AuthorizeCore
查看用户的身份并测试用户所处的角色。因此 returns 如果用户获得授权则为真。 (+)
对我来说,我删除了网站的 cookies 然后就可以了。似乎两个应用程序使用相同的数据库 table 来存储用户。更改 cookie 名称有助于解决错误:
您好,我正在尝试使用自定义授权属性,但 base.AuthorizeCore 总是 return 错误。我不知道我在哪里做错了。你能告诉我问题出在哪里吗?我的授权属性:
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();
}
很可能用户不在该角色中。 AuthorizeCore
查看用户的身份并测试用户所处的角色。因此 returns 如果用户获得授权则为真。 (+)
对我来说,我删除了网站的 cookies 然后就可以了。似乎两个应用程序使用相同的数据库 table 来存储用户。更改 cookie 名称有助于解决错误: