我有一个场景,在我的项目中,我必须处理Internet和Intranet两种模式。现在我必须根据模式应用滤镜,根据模式(有条件地)应用滤镜的最佳方法是什么。
执行此操作的一种方法是创建自定义过滤器提供程序并进行注册。但是如何以及何时可以检查应用程序模式。
谢谢, -Babu
答案 0 :(得分:1)
我们假设你正在使用Phil Haacked's Conditional Filter Provider:
public class ConditionalFilterProvider : IFilterProvider {
private readonly
IEnumerable<Func<ControllerContext, ActionDescriptor, object>> _conditions;
public ConditionalFilterProvider(
IEnumerable<Func<ControllerContext, ActionDescriptor, object>> conditions)
{
_conditions = conditions;
}
public IEnumerable<Filter> GetFilters(
ControllerContext controllerContext,
ActionDescriptor actionDescriptor) {
return from condition in _conditions
select condition(controllerContext, actionDescriptor) into filter
where filter != null
select new Filter(filter, FilterScope.Global, null);
}
}
并且您有两个自定义ActionFilterAttribute,称为IntranetAttribute和InternetAttribute。我们还要说所有Intranet请求都来自IP地址:10.122.122.12或10.122.122.13。
您可以在Application_Start中配置条件提供程序,如下所示:
private void ConfigureModeAttribute()
{
//Configure a conditional filter
string[] intranetIPs = { "10.122.122.12", "10.122.122.13" };
IEnumerable<Func<ControllerContext, ActionDescriptor, object>> conditions =
new Func<ControllerContext, ActionDescriptor, object>[] {
( c, a ) => intranetIPs.Contains(c.HttpContext.Request.UserHostAddress) ?
new IntranetAttribute() : new InternetAttribute()
};
var provider = new ConditionalFilterProvider(conditions);
// This line adds the filter we created above
FilterProviders.Providers.Add(provider);
}
希望它会对你有所帮助!