Ejemplo de comunicación remota: hospedar en Internet Information Services (IIS)

El ejemplo siguiente implementa un Servicio Web básico con complicaciones. Se utiliza formateador binario porque la carga útil es más compacta y el sistema tarda menos tiempo en serializar y deserializar la secuencia. Además, si Internet Information Services (IIS) está utilizando Autenticación de Windows integrada (también conocida como la autenticación NTLM), el servidor autentica al cliente y, a continuación, le devuelve la identidad que IIS ha autenticado. Finalmente, puede ayudar a proteger su Servicio Web cambiando la dirección URL en el archivo de configuración del cliente para utilizar "https" como el esquema de protocolos y configurar IIS para requerir el cifrado de Capa de sockets seguros (SSL) para esa directorio virtual (el ejemplo no muestra este proceso).

Precaución:

.La comunicación remota de .NET Framework no lleva a cabo la autenticación o el cifrado de forma predeterminada. Por consiguiente, se recomienda que dé todos los pasos necesarios para asegurarse de la identidad de los clientes o de los servidores antes de interactuar de forma remota con ellos. Dado que las aplicaciones remotas de .NET Framework exigen permisos FullTrust para ejecutarse, si a un cliente no autorizado se le permitiera el acceso a su servidor, el cliente podría ejecutar el código como si fuese un cliente de plena confianza. Autentique siempre sus extremos y cifre las secuencias de comunicación, ya sea hospedando sus tipos de utilización remota en IIS o generando un par del receptor de canal personalizado para hacer este trabajo.

Para compilar y ejecutar este ejemplo

  1. Guarde todos los archivos en un directorio denominado RemoteIIS.

  2. Compile la muestra completa escribiendo los comandos siguientes en el símbolo del sistema:

    [Visual Basic]

    vbc /t:library ServiceClass.vb
    vbc /r:System.Runtime.Remoting.dll /r:ServiceClass.dll Client.vb
    

    [C#]

    csc /t:library ServiceClass.cs
    csc /r:System.Runtime.Remoting.dll /r:ServiceClass.dll Client.cs
    
  3. Cree un subdirectorio \bin y copie ServiceClass.dll en ese directorio.

  4. Crear una aplicación en IIS. Cóncedale el alias "HttpBinary" a la aplicación y establezca el directorio de origen en el directorio "RemoteIIS."

  5. Establezca el método de autenticación para este directorio virtual a Autenticación de Windows integrada (denominada anteriormente autenticación NTLM). Si el acceso anónimo está seleccionado, HttpContext.Current.User.Identity.Name será null y GetServerString se convertirá en "***unavailable***" para el alias del usuario. Para evitar que esto se produzca, anule la selección del acceso anónimo.

  6. Asegúrese de que se inicia IIS; escriba cliente en el símbolo del sistema del directorio "RemoteIIS".

Esta aplicación se ejecuta en un solo equipo o a través de una red. Si desea ejecutar esta aplicación a través de una red, debe reemplazar "localhost" en la configuración del cliente por el nombre del equipo remoto.

ServiceClass

[Visual Basic]

Imports System
Imports System.Runtime.Remoting
Imports System.Web

Public Interface IService
    Function GetServerTime() As DateTime
    Function GetServerString() As String
End Interface

Public Class ServiceClass
    Inherits MarshalByRefObject
    Implements IService

    Private InstanceHash As Integer

    Public Sub New()
        InstanceHash = Me.GetHashCode()
    End Sub

    Public Function GetServerTime() As Date Implements IService.GetServerTime
        Return DateTime.Now
    End Function

    Public Function GetServerString() As String Implements IService.GetServerString
        ' Use the HttpContext to acquire what IIS thinks the client's identity is.
        Dim temp As String = HttpContext.Current.User.Identity.Name

        If (temp Is Nothing Or temp.Equals(String.Empty)) Then
            temp = "**unavailable**"
        End If

        Return "Hi there. You are being served by instance number: " _
            & InstanceHash.ToString() _
            & ". Your alias is: " _
            & temp
    End Function
End Class

[C#]

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

[Visual Basic]

Imports System
Imports System.Collections
Imports System.Net
Imports System.Runtime.Remoting
Imports System.Runtime.Remoting.Channels
Imports System.Security.Principal

Public Class Client

    Public Shared Sub Main()
        ' 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", False)

        ' New proxy for the ServiceClass.
        ' If you publish only the IService interface, you must use Activator.GetObject.
        Dim service As ServiceClass = New ServiceClass()

        ' Programmatically customizes the properties given to the channel. This sample uses the
        '  application configuration file.
        Dim Props As IDictionary = ChannelServices.GetChannelSinkProperties(service)
        Props.Item("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())
    End Sub
End Class

[C#]

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

class Client
{
    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", false);

        // 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

<?xml version="1.0" encoding="utf-8" ?>
<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>

Consulte también

Conceptos

Configuración de aplicaciones remotas
Hospedar objetos remotos en Internet Information Services (IIS)

Otros recursos

Ejemplos de comunicación remota

Copyright © 2007 Microsoft Corporation. Reservados todos los derechos.