filters.Add vs FilterProviders.Providers.Add

让人想犯罪 __ 提交于 2019-12-06 07:27:47

问题


I came across a sample MVC3 code which had following in the Global.asax file:

public static void RegisterGlobalFilters(....)
{
    filters.Add(new MyFilter1());
    ....
    var provider = new MyFilterProvider();
    provider.Add(c => c.HttpContext.IsDebuggingEnabled ? new MyProvider2() : null);
    FilterProviders.Providers.Add(provider)
}

Both MyProvider1 and MyProvider2 are implemented with IResultFilter, and I am confused why one of them is added to FilterProviders and the other one is registered as a global filter.

Why and when should we add custom filters on FilterProvider, and why and when should we register them as global filters?


回答1:


When you add a filter to GlobalFilters.Filters the filter will get executed for every request.

When you add an IFilterProvider to FilterProviders.Providers the filter provider will have a chance to decide whether a particular filter applies to the current request.

FilterProviders gives you greater control while GlobalFilters makes it easy to register a filter for the entire site.



来源:https://stackoverflow.com/questions/5312624/filters-add-vs-filterproviders-providers-add

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!