AllowAnonymous不工作MVC5

时间:2015-04-07 18:32:36

标签: 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();
    }

未经授权会将用户引导至此视图,但会导致重定向循环(可能是因为此过滤器仍在此页面上运行)。

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

2 个答案:

答案 0 :(得分:12)

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

尝试:

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

答案 1 :(得分:3)

检查自定义过滤器中的AllowAnonymousAttribute。这是一种可行的方法。

添加以下扩展方法。

public static class MyExtensionMethods
{
    public static bool HasAttribute(this ActionExecutingContext context, Type attribute)
    {
        var actionDesc = context.ActionDescriptor;
        var controllerDesc = actionDesc.ControllerDescriptor;

        bool allowAnon = 
            actionDesc.IsDefined(attribute, true) ||
            controllerDesc.IsDefined(attribute, true);

        return allowAnon;
    }
}

然后在过滤器中使用它。

public class MyActionFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // use the extension method in your filter
        if (filterContext.HasAttribute(typeof(AllowAnonymousAttribute)))
        {
            // exit early...
            return;
        }

        // ...or do whatever else you need to do
        if (user == null || !user.Active)
        {
            filterContext.Result = 
                new RedirectToRouteResult(new RouteValueDictionary
            {
                { "controller", "Home" }, 
                { "action", "NotAuthorized" }
            });
        }

        base.OnActionExecuting(filterContext);
    }
}

这是a fiddle that implements a solution