Exemplo do Sistema de Interação Remota: Hosting in Information Internet Serviços (IIS)
The seguinte exemplo Implements a Basic Web Serviço with a few complications. O BinaryFormatter é usado porque a carga é mais compacta e o sistema leva menos tempo para serializar e desserializar o fluxo. In addition, IF Information Internet Serviços (IIS) is Using Windows Integrated Authentication (also Known as NTLM autenticação), the servidor authenticates the cliente and then returns to the cliente the identidade that IIS was able to Authenticate. Finally, you can Ajuda Protect Your serviço da Web by Changing the URL in the arquivo de configuração cliente to use "https" as the esquema de protocolo and Configuring IIS to Require criptografia Secure Sockets Layer (SSL) for that diretório virtual (the exemplo not demonstrar this processo).
Aviso
.NET Framework Remoting não criptografia ou autenticação por padrão.Therefore, it is recommended that you Take All steps necessary to make Certain of the identidade of Clients or Servidores before interacting with them remotely.Because Applications Require Permissions FullTrust to , IF an Unauthorized were Granted on your , the Could Código as though IT were .Sempre autenticar seus pontos de extremidade e criptografar os fluxos de comunicação, por que hospeda seus tipos remotos em IIS ou por compilação um Personalizar coletor de canal par fazer esse trabalho.
Para compilar e executar esse exemplo
Salvar todas as Arquivos em um nomeado Diretório RemoteIIS.
Compile the entire exemplo by Digitação the seguinte Commands at the prompt de comando:
[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
Criar a \Bin subdiretório and copiar ServiceClass.dll into that Diretório.
Criar um aplicativo no IIS. Verifique o alias do Aplicativo "HttpBinary" e defina a pasta de origem para o diretório "RemoteIIS".
Defina o método de autenticação para esse diretório virtual para autenticação integrada do Windows (anteriormente conhecida como autenticação NTLM). If acessar Anonymous is Selecionado, HttpContext.Current.User.Identity.Name will be null and GetServerString will Return "***unavailable***" for the usuário alias. To evitar this from occuring, anular seleção Anonymous Acessar.
Certifique-se de que o IIS é iniciado; At the prompt de comando in the Diretório "RemoteIIS", tipo cliente.
This aplicativo Runs on a single computador OR Na Horizontal a rede. Se você deseja executar este aplicativo através de uma rede, você deve substituir "localhost" na configuração do cliente com o nome do computador 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>
Cliente.
[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());
}
}
Cliente. 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 também
Conceitos
Configuração de aplicativos remoto
Hosting Remoto Objects in Serviços de Informações da Internet (IIS)