Share via


方法 : HTTP トランスポートを使用します。

[このドキュメントはプレビュー版であり、後のリリースで変更されることがあります。 空白のトピックは、プレースホルダーとして挿入されています。]

HTTP トランスポートを使用して、デスクトップ上の Windows Communication Foundation (WCF) サービスに接続するデバイスでアプリケーションを作成することができます。

ここでは、クライアント アプリケーションを作成する方法と接続デバイスを処理する WCF サービスを構成する方法について説明します。 それには、あるモバイル デバイス、サービスへの接続を有効にすることを考慮する必要があります違い WCF サービスの構成とクライアント側のコーディングについて説明します。 デスクトップ用の WCF アプリケーションを作成する方法については、WCF ドキュメントでは、Getting Started Tutorial 参照してください。

デスクトップの WCF サービスを作成するには

  1. 新しい Web サービス プロジェクトを作成します。

  2. 次の例のように、Web.config ファイルを変更します。 次の要素と、ファイル内の属性を変更します。

    • Change the <endpoint>binding attribute value to "basicHttpBinding". .NET Compact Framework は、テキストのエンコーディングがないバイナリ エンコーディング サポートします。

    • 新しい動作の名前を参照する behaviorConfiguration 属性を変更します。

    • <behavior> 要素は、例のようにに置き換えます。

    • Web.config ファイルで HTTP サービス ハンドラーを登録する場合は、新しい <system.WebServer> 要素の例に示すように情報に追加します。

    <?xml version="1.0"?>
    
    <configuration xmlns="https://schemas.microsoft.com/.NetConfiguration/v2.0">
      <system.serviceModel>
        <services>
          <service name="CalculatorService" behaviorConfiguration="MyServiceTypeBehaviors">
            <endpoint contract="ICalculatorService" binding="basicHttpBinding"/>
          </service>
        </services>
        <behaviors>
          <serviceBehaviors>
            <behavior name="MyServiceTypeBehaviors">
              <serviceMetadata httpGetEnabled="true" />
              <serviceDebug httpHelpPageEnabled="true" includeExceptionDetailInFaults="true" />
            </behavior>
          </serviceBehaviors>
        </behaviors>
      </system.serviceModel>
    
      <system.web>
        <compilation debug="true"/>
      </system.web>
    
      <system.webServer>
        <handlers>
          <add name="HttpSvcHandler" path="*.svc" verb="*" type="System.ServiceModel.Activation.HttpHandler, System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" resourceType="Unspecified" />
        </handlers>
      </system.webServer>
    
    </configuration>
    
  3. WCF サービスのソース コードで、コードから属性を ServiceContractOperationContract で指定された任意のパラメーターを削除します。

    注意

    このサンプルは、ServiceContractOperationContract などの契約で指定されたパラメーターのサポートを実装しません。場合パラメーター サポート コントラクトは、WCF の .NET Compact Framework ServiceModel ユーティリティ ツール (NetCFSvcUtil.exe) を使用してクライアント コードを生成することができます。このツールはこれらのパラメーターの多くのサポート、.NET Compact Framework に基づくアプリケーションにビルドします。NetCFSvcUtil.exe は .NET Compact Frameworkの電源社で使用できます。 詳細については、 Power Toy .NET Compact Framework を参照してください。

    次の例を簡略化の電卓アプリケーションの WCF サービスのソース コードに示します。

    <ServiceContract()>  _
    PublicInterface ICalculatorService
        <OperationContract()>  _
        Function Add(ByVal n1 AsDouble, ByVal n2 AsDouble) AsDouble    '<OperationContract()>  _Function Subtract(ByVal n1 AsDouble, ByVal n2 AsDouble) AsDoubleEndInterfacePublicClass CalculatorService
        Implements ICalculatorService
    
        PublicFunction Add(ByVal n1 AsDouble, ByVal n2 AsDouble) AsDoubleImplements ICalculatorService.Add
            Return n1 + n2
    
        EndFunctionPublicFunction Subtract(ByVal n1 AsDouble, ByVal n2 AsDouble) AsDoubleImplements ICalculatorService.Subtract
            Return n1 - n2
    
        EndFunctionEndClass
    
    [ServiceContract()]
    publicinterface ICalculatorService
    {
        [OperationContract]
        double Add(double n1, double n2);
        [OperationContract]
        double Subtract(double n1, double n2);
    }
    
    publicclass CalculatorService : ICalculatorService
    {
        publicdouble Add(double n1, double n2) { return n1 + n2; }
        publicdouble Subtract(double n1, double n2) { return n1 - n2; }
    }
    
  4. Web サーバー上の特定のポートに、WCF サービスを設定します。

    10000 ~ 650000 の任意のポート番号を使います。 この例ではポート 50505 を使用します。

  5. Web サーバーを起動します。

    Web サービス記述言語 (WSDL) の出力を表示し、localhost に、サービスを実行する場合は、https://localhost:50505/CalculatorService/Service.svc?wsdl に移動します。 同じポート番号と指定した Web プロジェクト名を使用して、WCF サービス。

  6. 計画、リモート コンピューターまたはデバイスから、Web サーバーに接続している場合、Web プロジェクトを含むディレクトリを指す仮想ディレクトリを設定します。

    注意

    Visual Studio で ASP.NET 開発サーバーは、ローカルの開発コンピューターから要求にのみ応答します。仮想ディレクトリを指定する、インターネット インフォメーション サービス (IIS) を使用することを推奨します。これによって、サーバーが到達可能な限り、リモート デバイスから Web サーバーに接続できます。

  7. デスクトップ ブラウザーと、デバイスのブラウザーから、ディレクトリにアクセスできることを確認します。

.NET Compact Framework クライアントを作成するには

  1. サービスが実行中に、コマンドラインを開き、WCF サービスがあるディレクトリに移動します。

  2. コマンド プロンプトで WCF ServiceModel デスクトップ ユーティリティ ツール、WCF クライアント プロキシを生成するには、(SvcUtil.exe) を実行します。 ここでは、サービスが localhost でホストされている SvcUtil のコマンドライン、呼び出しの例です。

    svcutil.exe /language:c# https://localhost:50505/CalculatorService/Service.svc
    

    次の例の単純な電卓の例に基づく SvcUtil によって生成されたクライアント プロキシに示します。

                                //------------------------------------------------------------------------------
                                // <auto-generated>
                                //     This code was generated by a tool.
                                //     Runtime Version:2.0.50727.42
                                //
                                //     Changes to this file may cause incorrect behavior and will be lost if
                                //     the code is regenerated.
                                // </auto-generated>
                                //------------------------------------------------------------------------------
    
    
    
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
    [System.ServiceModel.ServiceContractAttribute(ConfigurationName="ICalculatorService")]
    publicinterface ICalculatorService
    {
    
        [System.ServiceModel.OperationContractAttribute(Action="https://fabrikam.com/ICalculatorService/Add", ReplyAction="https://fabrikam.com/ICalculatorService/AddResponse")]
        double Add(double n1, double n2);
    
        [System.ServiceModel.OperationContractAttribute(Action="https://fabrikam.com/ICalculatorService/Subtract", ReplyAction="https://fabrikam.com/ICalculatorService/SubtractResponse")]
        double Subtract(double n1, double n2);
    }
    
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
    publicinterface ICalculatorServiceChannel : ICalculatorService, System.ServiceModel.IClientChannel
    {
    }
    
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
    publicpartialclass CalculatorServiceClient : System.ServiceModel.ClientBase<ICalculatorService>, ICalculatorService
    {
    
        public CalculatorServiceClient()
        {
        }
    
        public CalculatorServiceClient(string endpointConfigurationName) : 
                base(endpointConfigurationName)
        {
        }
    
        public CalculatorServiceClient(string endpointConfigurationName, string remoteAddress) : 
                base(endpointConfigurationName, remoteAddress)
        {
        }
    
        public CalculatorServiceClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) : 
                base(endpointConfigurationName, remoteAddress)
        {
        }
    
        public CalculatorServiceClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) : 
                base(binding, remoteAddress)
        {
        }
    
        publicdouble Add(double n1, double n2)
        {
            returnbase.Channel.Add(n1, n2);
        }
    
        publicdouble Subtract(double n1, double n2)
        {
            returnbase.Channel.Subtract(n1, n2);
        }
    }
    
  3. サポートされていない属性と要素を次を含む、生成されたクライアント プロキシ コードから削除します。

    • すべての System.ServiceModel 属性。

    • IClientChannel クラスへの参照。

    • <endpoint> 構成名への参照。

    • 内部チャネル上で ServiceContract インターフェイスのメソッドが呼び出されるメソッドの実装。

    次の例これらの変更後のコードに示します。

                                '------------------------------------------------------------------------------
                                ' <auto-generated>
                                '     This code was generated by a tool.
                                '     Runtime Version:2.0.50727.312
                                '
                                '     Changes to this file may cause incorrect behavior and will be lost if
                                '     the code is regenerated.
                                ' </auto-generated>
                                '------------------------------------------------------------------------------
                                Option Strict Off
    Option Explicit OnPublicInterface ICalculatorService
    
        Function Add(ByVal n1 AsDouble, ByVal n2 AsDouble) AsDoubleFunction Subtract(ByVal n1 AsDouble, ByVal n2 AsDouble) AsDoubleEndInterfacePartialPublicClass CalculatorServiceClient
        Inherits System.ServiceModel.ClientBase(Of ICalculatorService)
        Implements ICalculatorService
    
        ' Add a variable containing the endpoint address.PublicShared ServiceEndPoint AsNew System.ServiceModel.EndpointAddress("https://fabrikam.com/CalcService/CalculatorService/Service.svc")
    
        PublicSubNew(ByVal binding As System.ServiceModel.Channels.Binding, ByVal remoteAddress As System.ServiceModel.EndpointAddress)
            MyBase.New(binding, remoteAddress)
        EndSubPublicFunction Add(ByVal n1 AsDouble, ByVal n2 AsDouble) AsDoubleImplements ICalculatorService.Add
            ReturnMyBase.Channel.Add(n1, n2)
        EndFunctionPublicFunction Subtract(ByVal n1 AsDouble, ByVal n2 AsDouble) AsDoubleImplements ICalculatorService.Subtract
            ReturnMyBase.Channel.Subtract(n1, n2)
        EndFunctionEndClass
    
                                //------------------------------------------------------------------------------
                                // <auto-generated>
                                //     This code was generated by a tool.
                                //     Runtime Version:2.0.50727.42
                                //
                                //     Changes to this file may cause incorrect behavior and will be lost if
                                //     the code is regenerated.
                                // </auto-generated>
                                //------------------------------------------------------------------------------
                                public
                                interface ICalculatorService
    {
    
        double Add(double n1, double n2);
    
        double Subtract(double n1, double n2);
    }
    
    publicpartialclass CalculatorServiceClient : System.ServiceModel.ClientBase<ICalculatorService>, ICalculatorService
    {
    
        // Add a variable to specify the server address.publicstatic System.ServiceModel.EndpointAddress ServiceEndPoint = new System.ServiceModel.EndpointAddress("https://fabrikam.com/CalcService/CalculatorService/Service.svc");
    
        public CalculatorServiceClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) : 
                base(binding, remoteAddress)
        {
        }
    
        publicdouble Add(double n1, double n2)
        {
            returnbase.Channel.Add(n1, n2);
        }
    
        publicdouble Subtract(double n1, double n2)
        {
            returnbase.Channel.Subtract(n1, n2);
        }
    }
    
  4. クライアント プロジェクトを作成します。

  5. プロジェクトに、生成されたクライアント プロキシを追加します。

  6. 生成されたプロキシ コード、内には、ユーザー定義 ClientBase<TChannel> クラスに ClientBase への完全限定参照を変更します。

  7. 生成されたプロキシ コードで、ユーザー定義 Call クラスの ClientBase メソッドを呼び出してメソッドの実装を追加します。

                                Public
                                Function Add(ByVal n1 AsDouble, ByVal n2 AsDouble) AsDoubleImplements ICalculatorService.Add
        Return System.Convert.ToDouble(MyBase.Call("Add", "https://fabrikam.com/CalcService/ICalculatorService/Add", NewString() {"n1", "n2"}, NewObject() {n1, n2}, GetType(Double)))
    EndFunction
    
                                public
                                double Add(double n1, double n2)
    {
        return (double)base.Call("Add", "https://fabrikam.com/CalcService/ICalculatorService/Add", newstring[] { "n1", "n2" }, newobject[] { n1, n2 }, typeof(double));
    }
    
  8. プロジェクトにプロキシの基本クラスを追加します。 このクラスを"ClientBase"と呼びます。

    ClientBase の実装を指すには、クライアント プロキシの基本クラス参照を変更します。

    注意

    次の使用例で CustomBodyWriterClientBase クラスは、プリミティブ型のみをサポートします。以外のプリミティブ型をサポートするには、OnWriteBodyContents メソッドを拡張です。たとえば、メッセージ データ シリアル化するカスタム シリアライザーを呼び出す可能性があります。ここでは、XML シリアライザーが消費する属性に、生成されたクライアント プロキシ内のコードの属性に変換しましょう。このシナリオでは、する必要がありますまず、次スイッチ追加 SvcUtil を実行するとします。/serializer:xmlserializer http://エンドポイント。

    ClientBase クラスの例を次のコードに示します。

                                Public
                                Class ClientBase(Of TChannel AsClass)
    
        Private requestChannel As IRequestChannel
        Private messageVersion As MessageVersion
    
    
        PublicSubNew(ByVal binding As System.ServiceModel.Channels.Binding, ByVal remoteAddress As System.ServiceModel.EndpointAddress)
            'this.remoteAddress = remoteAddress;Me.messageVersion = binding.MessageVersion
    
            Dim channelFactory As IChannelFactory(Of IRequestChannel)
            channelFactory = binding.BuildChannelFactory(Of IRequestChannel)(New BindingParameterCollection())
            channelFactory.Open()
            Me.requestChannel = channelFactory.CreateChannel(remoteAddress)
    
        EndSubPublicFunction [Call](ByVal op AsString, ByVal action AsString, ByVal varnames() AsString, ByVal varvals() AsObject, ByVal returntype As Type) AsObject
            requestChannel.Open(TimeSpan.MaxValue)
    
            Dim msg As Message = Message.CreateMessage(Me.messageVersion, action, New CustomBodyWriter(op, varnames, varvals, "<ns passed in from Proxy>"))
    
            Dim reply As Message = requestChannel.Request(msg, TimeSpan.MaxValue)
            Dim reader As XmlDictionaryReader = reply.GetReaderAtBodyContents()
            reader.ReadToFollowing(op + "Result")
            Return reader.ReadElementContentAs(returntype, Nothing)
    
        EndFunctionEndClassFriendClass CustomBodyWriter
        Inherits BodyWriter
        Private op AsStringPrivate varnames() AsStringPrivate varvals() AsObjectPrivate ns AsStringPublicSubNew(ByVal op AsString, ByVal varnames() AsString, ByVal varvals() AsObject, ByVal ns AsString)
            MyBase.New(True)
            Me.op = op
            Me.varnames = varnames
            Me.varvals = varvals
            Me.ns = ns
    
        EndSubProtectedOverridesSub OnWriteBodyContents(ByVal writer As XmlDictionaryWriter)
            writer.WriteStartElement(op, ns)
            Dim i AsIntegerFor i = 0 To varnames.Length
                writer.WriteElementString(varnames(i), varvals(i).ToString())
            Next i
            writer.WriteEndElement()
    
        EndSubEndClass
    
                                public
                                class ClientBase<TChannel>
        where TChannel : class
    {
        private IRequestChannel requestChannel;
        private MessageVersion messageVersion;
    
        public ClientBase(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress)
        {
            //this.remoteAddress = remoteAddress;this.messageVersion = binding.MessageVersion;
    
            IChannelFactory<IRequestChannel> channelFactory = binding.BuildChannelFactory<IRequestChannel>(
                new BindingParameterCollection());
            channelFactory.Open();
            this.requestChannel = channelFactory.CreateChannel(remoteAddress);
        }
    
        publicobject Call(string op, string action, string[] varnames, object[] varvals, Type returntype)
        {
            requestChannel.Open(TimeSpan.MaxValue);
    
            //Message msg =                     //Message.CreateMessage(MessageVersion.<FromBinding>,//      action,//      new CustomBodyWriter(op, varnames, varvals,               //"<ns passed in from Proxy>"));
    
            Message msg =                   
            Message.CreateMessage(this.messageVersion, action,
                  new CustomBodyWriter(op, varnames, varvals,               
            "<ns passed in from Proxy>"));
    
            Message reply = requestChannel.Request(msg, TimeSpan.MaxValue);
            XmlDictionaryReader reader = reply.GetReaderAtBodyContents();
            reader.ReadToFollowing(op + "Result");
            return reader.ReadElementContentAs(returntype, null);
        }
    
    }
    
    internalclass CustomBodyWriter : BodyWriter
    {
        privatestring op;
        privatestring[] varnames;
        privateobject[] varvals;
        privatestring ns;
    
        public CustomBodyWriter(string op, string[] varnames, object[] varvals, string ns)
            : base(true)
        {
            this.op = op;
            this.varnames = varnames;
            this.varvals = varvals;
            this.ns = ns;
        }
    
        protectedoverridevoid OnWriteBodyContents(XmlDictionaryWriter writer)
        {
            writer.WriteStartElement(op, ns);
            for (int i = 0; i < varnames.Length; i++)
                writer.WriteElementString(varnames[i], varvals[i].ToString());
            writer.WriteEndElement();
        }
    }
    
  9. 作成し、クライアント プロキシを使用してクラスを追加します。

    次の例をクライアント プロキシを呼び出すコードに示します。

                                Shared
                                Sub Main(ByVal args() AsString)
        Dim serverAddress AsString = CalculatorServiceClient.ServiceEndPoint.Uri.AbsoluteUri
        ' Using basic http connection. WS binding should be also available.Dim proxy As ICalculatorService = New CalculatorServiceClient(New BasicHttpBinding, New EndpointAddress(serverAddress))
        MessageBox.Show("Add 3 + 6...")
        MessageBox.Show(proxy.Add(3, 6).ToString)
        MessageBox.Show("Subtract 8 - 3...")
        MessageBox.Show(proxy.Subtract(8, 3).ToString)
    EndSub
    
                                static
                                void Main()
    {
        string serverAddress = CalculatorServiceClient.ServiceEndPoint.Uri.AbsoluteUri;
        // Using basic http connection. WS binding should be also available.
        ICalculatorService proxy = new CalculatorServiceClient(new BasicHttpBinding(), new EndpointAddress(serverAddress));
    
    
        MessageBox.Show("Add 3 + 6...");
        MessageBox.Show((proxy.Add(3, 6)).ToString());
        MessageBox.Show("Subtract 8 - 3...");        
        MessageBox.Show((proxy.Subtract(8, 3)).ToString());
    
    }
    
  10. クライアント アプリケーションをビルドし、デバイスに展開します。

  11. WCF サービスが実行されていると、デバイスがネットワークに接続されている、デバイス上でクライアント アプリケーションを起動します。

コードのコンパイル方法

WCF サービスのソース コードには、次の名前空間への参照が必要です。

ClientBase クラスのソース コードには、次の名前空間への参照が必要です。

クライアント アプリケーションで Main メソッドを格納するクラスのソース コードには、次の名前空間への参照が必要です。

セキュリティ

次の使用例は、WCF のセキュリティ機能を実装しません。 サポートされているセキュリティ機能の詳細については、.NET Compact Framework でメッセージング を参照してください。

参照

概念

.NET Compact Framework でメッセージング

その他の技術情報

Windows 通信基盤 (WCF) の開発と、.NET Framework を最適化します。