自定义授权属性不起作用

时间:2013-12-02 14:42:19

标签: authorize-attribute

我正在使用asp.net mvc4并在创建自定义授权属性时遇到问题。 我面临的问题是它继续使用这个“OnAuthorization”功能,而不是重定向到适当的区域。

这就是我想要做的事: -

这是我的自定义授权属性: -

public class BusinessAuthorizeFilter:IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationContext filterContext)
    {
        // if action or its controller has AllowAnonymousAttribute do nothing
        if filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute),
           true) ||filterContext.ActionDescriptor.ControllerDescriptor.IsDefined
           (typeof(AllowAnonymousAttribute), true))
            return;


         if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
        {
            RedirectToArea("Login", "Account", "");
            return;
        }



         if (filterContext.HttpContext.User.Identity.IsAuthenticated)
        {

          if (filterContext.HttpContext.User.IsInRole("Owner"))
              route = new RouteValueDictionary{  {"action", "Index"},
                                                 {"controller", "HomeAdmin"},
                                                  {"area", "Admin"}
                                              }
          else if (filterContext.HttpContext.User.IsInRole("Agent"))
               route = new RouteValueDictionary{  {"action", "Index"},
                                                 {"controller", "HomeAgent"},
                                                  {"area", "Agent"}
                                              }

           else
               route = new RouteValueDictionary{  {"action", "Index"},
                                                 {"controller", "HomeSalesRep"},
                                                  {"area", "SalesRep"}
                                              }

              }

         filterContext.Result = new RedirectToRouteResult(route);
}

请让我知道如何让它发挥作用。

提前致谢。

1 个答案:

答案 0 :(得分:0)

我让我的代码与下面的东西一起工作(虽然有一些问题我会发布作为其他问题): -

 public override void OnAuthorization(AuthorizationContext filterContext)
    {
         // if action or its controller has AllowAnonymousAttribute do nothing
        if (filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true) ||
            filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true))
            return;

        bool isAuthorize = base.AuthorizeCore(filterContext.HttpContext);

        if (!isAuthorize==true)
        {
            var result = new ViewResult();
            result.ViewName = "../Error/Unauthorized";
            filterContext.Result = result;
            return;
        }
}

实际上,我不是在这里重定向用户,而只是检查他是否是授权用户。