다음을 통해 공유


원격 서비스 예: IIS에서 호스팅

다음 샘플에서는 약간 복잡한 기본 웹 서비스를 구현합니다. BinaryFormatter를 사용하면 페이로드가 보다 적고 시스템에서 스트림을 serialize 및 deserialize하는 데 걸리는 시간이 줄어들기 때문에 이 샘플에서는 BinaryFormatter를 사용합니다. 또한 IIS(인터넷 정보 서비스)가 Windows 통합 인증(NTLM 인증이라고도 함)을 사용하는 경우 서버에서는 클라이언트를 인증한 다음 IIS가 인증할 수 있었던 ID를 클라이언트에게 반환합니다. 마지막으로, 클라이언트 구성 파일에서 URL을 변경하여 "https"를 프로토콜 스키마로 사용하고 IIS에서 해당 가상 디렉터리에 대해 SSL(Secure Sockets Layer) 암호화를 필요로 하도록 구성하면 웹 서비스를 보호할 수 있습니다. 샘플에서는 이 프로세스를 보여 주지 않습니다.

경고

.NET Framework Remoting에서는 기본적으로 인증이나 암호화 작업을 수행하지 않습니다. 따라서 원격으로 클라이언트나 서버와 상호 작용하기 전에 클라이언트나 서버의 ID를 확인하는 데 필요한 모든 단계를 수행하는 것이 좋습니다. .NET Framework Remoting 응용 프로그램을 실행하려면 FullTrust 권한이 필요하므로 권한이 없는 클라이언트에게 서버에 대한 액세스 권한을 부여하면 해당 클라이언트는 완전 신뢰 상태처럼 코드를 실행할 수 있습니다. IIS에서 원격화된 형식을 호스팅하거나 사용자 지정 채널 싱크 쌍을 만들어서 항상 끝점을 인증하고 통신 스트림을 암호화하십시오.

이 샘플을 컴파일하고 실행하려면

  1. RemoteIIS라는 디렉터리에 모든 파일을 저장합니다.

  2. 명령 프롬프트에 다음 명령을 입력하여 전체 샘플을 컴파일합니다.

    csc /noconfig /t:library /r:System.Web.dll /out:ServiceClass.dll ServiceClass.cs

    csc /noconfig /r:System.Runtime.Remoting.dll /r:System.dll /r:ServiceClass.dll Client.cs

  3. \bin 하위 디렉터리를 만들고 ServiceClass.dll을 이 디렉터리에 복사합니다.

  4. IIS에서 가상 디렉터리를 만듭니다. 가상 디렉터리 별칭을 "HttpBinary"로 만들고 소스 디렉터리를 "RemoteIIS" 디렉터리로 설정합니다.

  5. 이 가상 디렉터리의 인증 메서드를 Windows 통합 인증(이전의 NTLM 인증)으로 설정합니다.

  6. IIS가 시작되었는지 확인한 다음 "RemoteIIS" 디렉터리의 명령 프롬프트에서 client를 입력합니다.

이 응용 프로그램은 한 컴퓨터나 네트워크에서 실행됩니다. 이 응용 프로그램을 네트워크에서 실행하려는 경우 클라이언트 구성의 **"localhost"**를 원격 컴퓨터의 이름으로 바꿔야 합니다.

ServiceClass.cs

using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Threading;
using System.Web;

public interface IService{

   DateTime GetServerTime();
   string GetServerString();

}

// IService exists to demonstrate the possibility of publishing only the interface.
public class ServiceClass : MarshalByRefObject, IService{

   private int InstanceHash;

   public ServiceClass(){
      InstanceHash = this.GetHashCode();
   }

   public DateTime GetServerTime(){
      return DateTime.Now;
   }

   public string GetServerString(){
      // Use the HttpContext to acquire what IIS thinks the client's identity is.
      string temp = HttpContext.Current.User.Identity.Name;
      if (temp == null || temp.Equals(string.Empty))
         temp = "**unavailable**";
      return "Hi there. You are being served by instance number: " 
         + InstanceHash.ToString() 
         + ". Your alias is: " 
         + temp;
   }
}

Web.config

<configuration>
   <system.runtime.remoting>
      <application>
         <service>
            <wellknown 
               mode="SingleCall" objectUri="SAService.rem"
               type="ServiceClass, ServiceClass"/>
         </service>
         <channels>
            <channel ref="http"/>
         </channels>
      </application>
   </system.runtime.remoting>
</configuration>

Client.cs

using System;
using System.Collections;
using System.Diagnostics;
using System.Net;
using System.Reflection;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Security.Principal;

public class Client{

   public static void Main(string[] Args){

         // Tells the system about the remote object and customizes the HttpChannel
         // to use the binary formatter (which understands that base64 encoding is needed).
         RemotingConfiguration.Configure("Client.exe.config");

         // New proxy for the ServiceClass.
         // If you publish only the IService interface, you must use Activator.GetObject.
         ServiceClass service = new ServiceClass(); 
            
         // Programmatically customizes the properties given to the channel. This sample uses the
         // application configuration file.
         // IDictionary Props = ChannelServices.GetChannelSinkProperties(service);
         // Props["credentials"] = CredentialCache.DefaultCredentials;

         // Reports the client identity name.
         Console.WriteLine("ConsoleIdentity: " + WindowsIdentity.GetCurrent().Name);

         // Writes what the server returned.
         Console.WriteLine("The server says : " + service.GetServerString());
         Console.WriteLine("Server time is: " + service.GetServerTime());      
   }
}

Client.exe.config

<configuration>
   <system.runtime.remoting>
      <application>
         <channels>
            <channel ref="http" useDefaultCredentials="true" port="0">
               <clientProviders>
                  <formatter 
                     ref="binary"
                  />
               </clientProviders>
            </channel>
         </channels>
         <client>
            <wellknown 
               url="https://localhost:80/HttpBinary/SAService.rem"
               type="ServiceClass, ServiceClass"
            />
         </client>
      </application>
   </system.runtime.remoting>
</configuration>

참고 항목

개념

원격 응용 프로그램의 구성
IIS에서 원격 개체 호스팅

기타 리소스

원격 서비스 예