2013-10-28 6 views
0

시나리오가 있습니다. 내 프로젝트에서 인터넷과 인트라넷의 두 가지 모드를 처리해야합니다. 이제는 모드를 기반으로 필터를 적용해야합니다 (조건에 따라) 모드를 기반으로 필터를 적용하는 가장 좋은 방법은 무엇입니까?MVC 조건부 필터 공급자

이렇게하는 한 가지 방법은 사용자 지정 필터 공급자를 만들고 등록하는 것입니다. 언제 어떻게 응용 프로그램 모드를 확인할 수 있습니까?

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

을 그리고 당신은 IntranetAttribute 및 InternetAttribute라는 두 개의 사용자 정의 ActionFilterAttribute을 가지고 :

감사합니다, -Babu

+0

인트라넷이나 인터넷에서 사용자가 어떤 네트워크인지 쉽게 알 수 있습니까? 예 : 인트라넷 IP가 10, 172 또는 192로 시작합니까? – Mark

+0

맞습니다.하지만 질문은 조건부 필터를 적용하는 것과 관련이 있습니다. – Babu

답변

1

은의 당신이 Phil Haacked's Conditional Filter Provider를 사용하는 가정하자. 모든 인트라넷 요청은 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); 
    } 

그것은 당신을 도울 것입니다 희망!

+0

답변을 게시 해 주셔서 감사합니다! 이 사이트의 대답의 핵심 부분을이 사이트에 게시하거나 게시물의 위험 요소를 삭제해야합니다. [링크보다 간신히 답을 제시하는 FAQ를 참조하십시오.] (http : // stackoverflow. co.kr/faq # deletion) 원하면 '참조'로만 링크를 포함 할 수 있습니다. 대답은 링크가 필요없이 독자적으로 서 있어야합니다. – Taryn

+0

좋아, @ 블루피트, 나는 그것을 밖으로 fleshed했습니다. –

+1

답변을 주셔서 감사합니다 이것은 동일합니다, 구현했습니다. – Babu