Asp.net mvc 4 &引用;试图执行未经授权的操作”;使用CustomRoleProvider时
我编写了一个自定义角色提供程序:Asp.net mvc 4 &引用;试图执行未经授权的操作”;使用CustomRoleProvider时,asp.net-mvc-4,forms-authentication,roleprovider,Asp.net Mvc 4,Forms Authentication,Roleprovider,我编写了一个自定义角色提供程序: public class CustomRoleProvider : RoleProvider { public override string[] GetRolesForUser(string username) { var rolesService = ObjectFactory.GetInstance<IRoleService>(); return rolesSe
public class CustomRoleProvider : RoleProvider
{
public override string[] GetRolesForUser(string username)
{
var rolesService = ObjectFactory.GetInstance<IRoleService>();
return rolesService.GetRolesForUser(username.ToInt());
}
public override bool IsUserInRole(string username, string roleName)
{
var rolesService = ObjectFactory.GetInstance<IRoleService>();
return rolesService.IsUserInRole(username.ToInt(), roleName);
}
//....
}
我还编写了一个自定义授权属性:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class SiteAuthorizeAttribute : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Request.IsAuthenticated)
{
throw new UnauthorizedAccessException(); //to avoid multiple redirects
}
else
{
base.HandleUnauthorizedRequest(filterContext);
}
}
}
但是,当我在登录后使用[sitearization(Roles=“Admins”)]
装饰控制器或操作方法时,我遇到以下错误:
Attempted to perform an unauthorized operation.
源错误:
Line 14: if (filterContext.HttpContext.Request.IsAuthenticated)
Line 15: {
Line 16: throw new UnauthorizedAccessException(); //to avoid multiple redirects
Line 17: }
Line 18: else
我很难找到我的问题并把我搞砸了,有人能帮我找出我的问题在哪里吗?PS:当我在其他视图中检查
User.Identity.Name
的值时,它是0,我还在web.config
中检查身份验证类型:
<roleManager enabled="true" defaultProvider="CustomRoleProvider">
<providers>
<clear/>
<add name="CustomRoleProvider"
type="PooyanTKD.Web.Infrastructure.CustomRoleProvider"
connectionStringName="DefaultConnection"
enablePasswordRetrieval="false" enablePasswordReset="true"
requiresQuestionAndAnswer="false" writeExceptionsToEventLog="false" />
</providers>
</roleManager>
<forms name="Sir1Afifi2013"
cookieless="UseCookies"
loginUrl="~/Account/LogOn"
defaultUrl="~/Admin/Main"
slidingExpiration="true"
protection="All"
path="/"
timeout="20" />
</authentication>
提前感谢最后,我通过将未经授权的用户重定向到另一个路由,解决了我的问题:
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Request.IsAuthenticated)
{
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
{
action = "Index",
controller = "Home",
area = ""
}));
}
else
{
base.HandleUnauthorizedRequest(filterContext);
}
}
抱歉亲爱的@Sirwan Afifi