Partager via


Exemple d'accès distant : hébergement dans Internet Informations Services (IIS)

L'exemple suivant implémente un service Web de base avec quelques complications. BinaryFormatter est utilisé car la charge est plus compacte et le système a besoin de moins de temps pour sérialiser et désérialiser le flux. En outre, si IIS (Internet Information Services) utilise l'authentification intégrée Windows (également appelée authentification NTLM), le serveur authentifie le client, puis retourne au client l'identité que IIS a été en mesure d'authentifier. Enfin, vous pouvez protéger votre service Web en changeant l'URL dans le fichier de configuration client pour utiliser « https » comme modèle de protocole et en configurant IIS pour qu'il exige un cryptage SSL (Secure Sockets Layer) pour ce répertoire virtuel (l'exemple n'illustre pas ce processus).

ATTENTION   .NET Remoting n'effectue aucune authentification ni aucun cryptage par défaut. Par conséquent, il est recommandé d'effectuer toutes les opérations nécessaires pour vous assurer de l'identité des clients ou des serveurs avant d'interagir avec eux à distance. Étant donné que les applications .NET Remoting exigent les autorisations FullTrust pour s'exécuter, si un client non autorisé se voyait accorder l'accès à votre serveur, il pourrait exécuter du code comme s'il était d'un niveau de confiance suffisant. Authentifiez toujours vos points d'entrée et cryptez les flux de communication, en hébergeant vos types distants dans IIS ou en créant une paire de récepteurs de canal personnalisée pour effectuer cette tâche.

Pour compiler et exécuter cet exemple

  1. Enregistrez tous les fichiers dans un répertoire nommé RemoteIIS.

  2. Compilez l'exemple entier en tapant les commandes suivantes à l'invite de commande :

    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. Créez un sous-répertoire \bin et copiez ServiceClass.dll dans ce répertoire.

  4. Créez un répertoire virtuel dans IIS. Nommez l'alias du répertoire virtuel « HttpBinary » et définissez le répertoire « RemoteIIS » comme répertoire source.

  5. Sélectionnez la méthode d'authentification intégrée Windows (Integrated Windows Authentication, anciennement nommée authentification NTLM) comme méthode d'authentification de ce répertoire virtuel.

  6. Assurez-vous que IIS est en cours d'exécution ; à l'invite de commande du répertoire « RemoteIIS », tapez client.

Cette application s'exécute sur un ordinateur unique ou sur un réseau. Si vous voulez exécuter cette application sur un réseau, vous devez remplacer « localhost » dans la configuration du client par le nom de l'ordinateur distant.

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>

Voir aussi

Exemples d'accès distant | Configuration | Hébergement d'objets distants dans Internet Information Services (IIS)