Подтвердить что ты не робот

Способ исключения фильтров действий в ASP.NET MVC?

Я столкнулся с несколькими случаями в ASP.NET MVC, где я хотел применить фильтр действий для каждого действия, кроме одного или двух. Например, скажем, у вас есть AccountController. Каждое действие в нем требует входа пользователя в систему, поэтому вы добавляете [Авторизовать] на уровне контроллера. Но скажите, что вы хотите включить страницу входа в AccountController. Проблема в том, что пользователи, отправленные на страницу входа в систему, не авторизованы, поэтому это приведет к бесконечному циклу.

Очевидное исправление (кроме перемещения действия входа на другой контроллер) заключается в перемещении [Авторизовать] с контроллера на все методы действий, кроме Login. Ну, это не весело, особенно когда у вас много методов или забыть добавить [Авторизовать] к новому методу.

Rails делает это легко с возможностью исключения фильтров. ASP.NET MVC не позволяет вам. Поэтому я решил сделать это возможным, и это было легче, чем я думал.

    /// <summary>
/// This will disable any filters of the given type from being applied.  This is useful when, say, all but on action need the Authorize filter.
/// </summary>
[AttributeUsage(AttributeTargets.Method|AttributeTargets.Class, AllowMultiple=true)]
public class ExcludeFilterAttribute : ActionFilterAttribute
{

    public ExcludeFilterAttribute(Type toExclude)
    {
        FilterToExclude = toExclude;
    }

    /// <summary>
    /// The type of filter that will be ignored.
    /// </summary>
    public Type FilterToExclude
    {
        get;
        private set;
    }
}

/// <summary>
/// A subclass of ControllerActionInvoker that implements the functionality of IgnoreFilterAttribute.  To use this, just override Controller.CreateActionInvoker() and return an instance of this.
/// </summary>
public class ControllerActionInvokerWithExcludeFilter : ControllerActionInvoker
{
    protected override FilterInfo GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
    {
        //base implementation does all the hard work.  we just prune off the filters to ignore
        var filterInfo = base.GetFilters(controllerContext, actionDescriptor);           
        foreach( var toExclude in filterInfo.ActionFilters.OfType<ExcludeFilterAttribute>().Select(f=>f.FilterToExclude).ToArray() )
        {
            RemoveWhere(filterInfo.ActionFilters, filter => toExclude.IsAssignableFrom(filter.GetType()));
            RemoveWhere(filterInfo.AuthorizationFilters, filter => toExclude.IsAssignableFrom(filter.GetType()));
            RemoveWhere(filterInfo.ExceptionFilters, filter => toExclude.IsAssignableFrom(filter.GetType()));
            RemoveWhere(filterInfo.ResultFilters, filter => toExclude.IsAssignableFrom(filter.GetType()));
        }
        return filterInfo;
    }


    /// <summary>
    /// Removes all elements from the list that satisfy the condition.  Returns the list that was passed in (minus removed elements) for chaining.  Ripped from one of my helper libraries (where it was a pretty extension method).
    /// </summary>
    private static IList<T> RemoveWhere<T>(IList<T> list, Predicate<T> predicate)
    {

        if (list == null || list.Count == 0)
            return list;
        //note: didn't use foreach because an exception will be thrown when you remove items during enumeration
        for (var i = 0; i < list.Count; i++)
        {
            var item = list[i];
            if (predicate(item))
            {
                list.RemoveAt(i);
                i--;
            }
        }
        return list;
    }
}

/// <summary>
/// An example of using the ExcludeFilterAttribute.  In this case, Action1 and Action3 require authorization but not Action2.  Notice the CreateActionInvoker() override.  That necessary for the attribute to work and is probably best to put in some base class.
/// </summary>
[Authorize]
public class ExampleController : Controller
{
    protected override IActionInvoker CreateActionInvoker()
    {
        return new ControllerActionInvokerWithExcludeFilter();
    }

    public ActionResult Action1()
    {
        return View();
    }

    [ExcludeFilter(typeof(AuthorizeAttribute))]
    public ActionResult Action2()
    {
        return View();
    }

    public ActionResult Action3()
    {
        return View();
    }

}

Пример здесь. Как вы можете видеть, это было довольно просто сделать и отлично работает. Надеюсь, это полезно для всех?

4b9b3361

Ответ 1

Я предпочитаю решение, описанное здесь здесь. Хотя это не так общее решение, как ваше, я нашел его немного более простым.

В моем случае я искал способ включить CompressionFilter на все, кроме нескольких элементов. Поэтому я создал пустой атрибут, подобный этому:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public sealed class DisableCompression : Attribute { }

Затем в главном атрибуте проверьте наличие атрибута следующим образом:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class CompressionFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        bool disabled = filterContext.ActionDescriptor.IsDefined(typeof(DisableCompression), true) ||
                        filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(DisableCompression), true);
        if (disabled)
            return;

        // action filter logic here...
    }
}

Хотя страница, на которую я ссылаюсь, упоминает, что это для MVC 3, кажется, что она работает достаточно хорошо и в MVC 1.

EDIT: покажем некоторое использование здесь в ответ на комментарии. Прежде чем я внес изменения, это выглядело точно так же, как и без атрибута [DisableCompression], помеченного методом, который я хотел исключить. Там не было другого рефакторинга.

[CompressionFilter]
public abstract class BaseController : Controller
{
}

public class SomeController : BaseController
{
    public ActionResult WantThisActionCompressed()
    {
        // code
    }

    [DisableCompression]
    public ActionResult DontWantThisActionCompressed()
    {
        // code
    }
}

Ответ 2

Я полагаю, что много лет назад атрибут [AllowAnnonymous] не был добавлен в ASP.NET MVC. Сегодня у меня может быть атрибут [Authorize] поверх моего контроллера, применимый ко всем методам Action, и я просто просто переопределяю это в Actions, я требую неавторизованных пользователей, добавляя атрибуты [AllowAnonymous] к конкретным действиям.