【问题标题】:Child actions are not allowed to perform redirect actions exception on filter added to Global Filters [duplicate]不允许子操作对添加到全局过滤器的过滤器执行重定向操作异常[重复]
【发布时间】:2015-04-17 14:27:09
【问题描述】:

我正在尝试实现一个横切授权属性,但我不断收到异常 -

Exception: Child actions are not allowed to perform redirect actions

这是我的代码:

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new MyAuthorizeAttribute(new List<string>(), new List<string>()));
    }
}

public class MyAuthorizeAttribute : AuthorizeAttribute
{
    public MyAuthorizeAttribute(IEnumerable<string> permittedRoles = null, IEnumerable<string> permittedUsers = null)
    {
        if (permittedRoles != null) Roles = string.Join(",",permittedRoles);
        if (permittedUsers != null) Users = string.Join(",",permittedUsers);
    }

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        filterContext.Result =
            new RedirectToRouteResult(new RouteValueDictionary
            {
                {"controller", "NotAuthorized"},
                {"action", "Index"}
            });
    }
}

有什么可以让我继续使用MyAuthorizeAttribute 作为全局过滤器的吗?

【问题讨论】:

  • 好路标问题,我也不认为你需要单独的答案。
  • 我认为您的问题/自我回答没有任何问题。我仍然认为它是重复的,因为链接的answer 涵盖了如何做到这一点(以一种比您的答案中显示的更简单的方式)以及解释“子操作”和检查本身的含义。
  • 我不确定...“如果您希望(或不希望)在正在执行的操作是子操作时执行某些特定操作,请检查 filterContext.IsChildAction 属性。”感觉就像是您问题的准确答案。
  • @AlexeiLevenkov:我刚刚看了这两个问题,它们看起来完全不同。这个问题是问他为什么会得到一个exception。另一个是问什么是ChildAction。我将投票重新开放,理由是它们足够不同和不同的问题。
  • C Bauer 正如我所说,我认为这是一个很好的问题(从搜索的角度来看也足够独特),因此值得保留作为重复,只是回答部分并不是绝对必要的(但绝对没有错) .所以我不会删除它。或者,您可以更新以以@MikeBantegui 阅读问题的方式旋转它 - 编辑/评论,如果您打算更改它,我将撤回我的投票(您可能不得不提出不同的答案,所以:)) .

标签: c# model-view-controller filter authorization


【解决方案1】:

HandleUnauthorizedRequest开头添加如下sn-p:

if (filterContext.IsChildAction)
{
     return;
}

这将中止子操作的重定向。

或者,您可以使用[AllowAnonymous] 禁用所有仅作为子级调用的控制器的属性。它还可以用来装饰您的“未授权”控制器以停止重定向。

猜你喜欢
  • 2021-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多