2011-05-05 7 views
25

방금 ​​ASP.NET AJAX에서 WCF 서비스를 사용하기 시작했습니다. Javascript에서 내 WCF 서비스를 인스턴스화 한 다음 문자열 변수를 인수로 사용하여 WCF Service 메서드 (OperationContract 서명 포함)에 전달합니다. 그런 다음 내 사용자 지정 Javascript 클래스에 바인딩 된 .NET 개체 (DataContract로 정의 됨)를 반환합니다. 내 웹 세션에 로그인 한 사용자를 기반으로 인증하는 데 문제가 있습니다. 그러나 WCF 웹 서비스는 HttpContext.Current 개체에 대한 컨텍스트가없는 완전히 다른 서비스입니다. 객체에 액세스하는 가장 안전한 방법은 무엇입니까?WCF 웹 서비스에서 HttpContext.Current에 액세스하십시오.

답변

44

당신은 바람직하게 구성을 통해, AspNetCompatibility을 가능하게하여 HttpContext.Current에 액세스 할 수 있습니다 :

<configuration> 
    <system.serviceModel> 
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/> 
    </system.serviceModel> 
</configuration> 

그러면 차례대로 현재 사용자 (HttpContext.Current.User)에 액세스 할 수 있습니다.

당신은 추가 속성으로 서비스 클래스를 장식하여 AspNetCompatibility을 적용 할 수 있습니다 : (. System.ServiceModel.Activation 네임 스페이스에서)

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)] 

을 그 속성이 장소에있는 경우, 서비스가 AspNetCompatibility가 아닌 시작되지 않습니다 사용 가능!

+0

입력 해 주셔서 감사합니다. 나는 너에게 한 가지를 주었다. 나는 이것을 시험해 본 후에 대답을 표시 할 것이다. 우리는 애플리케이션에 사용자를 약간 다르게 저장하므로 양식 인증을 위해 권장하는대로 재 설계해야합니다. 그런 다음이 방법을 사용할 수 있습니다. – MacGyver

+0

서비스가 IIS에서 호스팅되는 경우에만 작동한다는 점은 주목할 가치가 있습니다. –

22

당신은 HttpContext를 기본적으로하지 않습니다하지만 당신은 (항상 존재)에 OperationContext에 존재하는 동일한 개체 또는 특정 바인딩 만 사용할 수있는 WebOperationContext (많은있다.

당신은에 액세스 할 수 있습니다 그래서 같은 정적 .Current 속성을 사용하여 OperationContext 또는 WebOperationContext : WebOperationContext.Current

+4

일이이 허용 대답해야합니다. WCF는 Windows 서비스에서 호스팅되거나 자체 호스팅 될 수 있습니다. AspNetCompatilibity는 오래된 습관 일뿐입니다. – Askolein

2

이 경우 당신은의 Web.config를 변경하지 않으하거나 변경할 수 없습니다 :

private string GetClientIPAddress() 
     { 
      var props = OperationContext.Current.IncomingMessageProperties; 
      var endpointProperty = props[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty; 
      if (endpointProperty != null) 
      { 
       if (endpointProperty.Address == "::1" || String.IsNullOrEmpty(endpointProperty.Address)) 
        return "127.0.0.1"; 

       return endpointProperty.Address; 
      } 

      return String.Empty; 
     } 
관련 문제