c# - AllowAnonymous 不工作 MVC5

标签 c# asp.net-mvc asp.net-mvc-5

我正在使用自定义过滤器(定义如下):

        if (user == null || !user.Active)
        {
            filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary
            {
                {"controller", "Home"},
                {"action", "NotAuthorized"}
            });
        }
        base.OnActionExecuting(filterContext);

这是在站点范围内运行的(在 FilterConfig.cs 内的 RegisterGlobalFilters() 中。但是,我想允许访问一个页面 - NotAuthorized 页面。在 HomeController 中,我已创建以下 ActionResult 方法:

    [AllowAnonymous]
    public ActionResult NotAuthorized()
    {
        return View();
    }

未经授权确实会导致用户进入此 View ,但会导致重定向循环(可能是因为过滤器仍在该页面上运行)。

如何允许匿名用户访问此页面?

最佳答案

您需要检查自定义过滤器中的属性。

尝试:

if (!filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), false)
    && !filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), false)
    && (user == null || !user.Active))
{
    //....
}

关于c# - AllowAnonymous 不工作 MVC5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29498683/

相关文章:

c# - ASP.MVC 的显示值转换器

c# - MVC4 通过 Ajax.BeginForm 传递模型

c# - Enum.Parse 返回意外成员

C# 部署项目 : Icon doesn't appear for the extension associated

jquery - $(document).ready() 在加载部分 View 之前触发

asp.net-mvc-5 - XsrfKey 的用途是什么?我应该将 XsrfId 设置为其他内容吗?

c# - MVC Controller : Using LINQ to check for duplicate value already existing in table before Save?

c# - 如何强制执行 C#/.NET 的代码样式,例如 IDE0058、IDE0059 和 IDE0060?

c# - 在 C# 中阻止函数调用

asp.net-mvc - 你如何强制 IIS Express 默认为 https URL?