0

我试图实现一个 AuthorizeAttribute 以便我可以将其应用于某些子操作,其目的是例如在该人被授权并有权访问时显示菜单,否则返回没有错误或重定向到登录页面。我尝试了几种不同的退货选项,但都没有成功。下面的例子

//SideMenu.cshtml
    @{Html.RenderAction("AdminMenu", "Menu", "Menu");}

    @{Html.RenderAction("CommitteeMenu", "Menu", "Menu");}

    @{Html.RenderAction("MemberMenu", "Menu", "Menu");}

    @{Html.RenderAction("PublicMenu", "Menu", "Menu");}

//MenuController
         [BlockChildContentAuthorize(Roles = " Committee, Admin, Full_rights")]
         [ChildActionOnly]
         public virtual ActionResult CommitteeMenu()
         {
                 ....
         }

//Authorize.cs     
    public class BlockChildContentAuthorizeAttribute : AuthorizeAttribute
        {    

            protected override void HandleUnauthorizedRequest(System.Web.Mvc.AuthorizationContext filterContext)
            {
                if (filterContext.IsChildAction)
                {
                    if (filterContext.HttpContext.Request.IsAuthenticated)
                    {

                    }
                    else
                    {
                        filterContext.Result = new System.Web.Mvc.HttpStatusCodeResult(HttpStatusCode.Unauthorized);

                        return;
                    }
                }
            }
    }
4

1 回答 1

0

您不能直接从自定义属性操作视图,如果用户未通过身份验证,请尝试这样的操作创建一个视图包并在视图中检查它。

    protected override void HandleUnauthorizedRequest(System.Web.Mvc.AuthorizationContext filterContext)
        {
         filterContext.Controller.ViewBag.IsAuthenticated = true;             
         if (filterContext.IsChildAction)
                {
                  if (!filterContext.HttpContext.Request.IsAuthenticated)
                  {
                  //User is not authenticated, Redirect to login page                                              
                  filterContext.Controller.ViewBag.IsAuthenticated = false;
                    }
                 //else user is authenticated, do nothing Action result will be executed.
                }else
               {
                 // not child action, perform operation.
               }         
        }

查看 - SideMenu.cshtml - 未经身份验证的用户看不到委员会菜单链接(例如)

    @{Html.RenderAction("AdminMenu", "Menu", "Menu");}
     @if(ViewBag.IsAuthenticated)
     {
     Html.RenderAction("CommitteeMenu", "Menu", "Menu");
     }
     @{Html.RenderAction("MemberMenu", "Menu", "Menu");}
     @{Html.RenderAction("PublicMenu", "Menu", "Menu");}

或者,您可以直接在视图中检查用户身份验证,这样就可以避免自定义属性。

    //SideMenu.cshtml
    @{Html.RenderAction("AdminMenu", "Menu", "Menu");}
    @if(HttpContext.Current.Request.IsAuthenticated)
    {
      Html.RenderAction("CommitteeMenu", "Menu", "Menu");
    }
    @{Html.RenderAction("MemberMenu", "Menu", "Menu");}
    @{Html.RenderAction("PublicMenu", "Menu", "Menu");}
于 2013-07-21T15:36:02.493 回答