MVC条件过滤器供应商 [英] MVC Conditional filter Provider

查看:142
本文介绍了MVC条件过滤器供应商的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个场景,在我的项目,我要处理两种模式Internet和Intranet。现在我有一个基于模式以应用过滤器,什么是应用基于模式的过滤器的最佳方法(条件)。

I have a scenario, In my project where I have to handle two modes Internet and Intranet. Now I have to apply the filters based on the Modes, what is the best way to apply the filters based on the modes(conditionally).

做到这一点的方法是创建自定义过滤器供应商,注册。但如何当我可以检查应用模式。

One way to do this is to create custom filter provider and register it. but how and when I can check the application mode.

谢谢,
-Babu

Thanks, -Babu

推荐答案

让我们假设你正在使用的菲尔Haacked的条件筛选器提供商

Let's assume you're using 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

And that you have two custom ActionFilterAttribute, called IntranetAttribute and InternetAttribute. Let's also say that all Intranet requests will come from either IP address: 10.122.122.12 or 10.122.122.13.

您可以配置的Application_Start这样的条件提供者:

You can configure the Conditional Provider in Application_Start like this:

    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);
    }

希望它会帮助你!

Hope it will help you!

这篇关于MVC条件过滤器供应商的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆