吉吉于

WCF笔记1:metadata

采用wsHttpBinding绑定。

下面的代码显示了wsHttpBinding绑定的地址格式:
http://{hostname}:{port}/{service location}
https://{hostname}:{port}/{service location}
http协议的默认端口是80而https的默认端口是443。
实现metadata暴露的方法有二:
1.在Hosting代码中编写:
using System;
using System.ServiceModel;
using System.ServiceModel.Description;
using Contracts;
using Services;

namespace Hosting
{
    class Program
    {
        static void Main(string[] args)
        {
            using (ServiceHost host = new ServiceHost(typeof(Services.Services)))
            {
                host.AddServiceEndpoint(typeof(ICaculator), new WSHttpBinding(), "http://127.0.0.1:9999/calculatorservice");
                if (host.Description.Behaviors.Find<ServiceMetadataBehavior>() == null)
                {
                    ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
                    behavior.HttpGetEnabled = true;
                    behavior.HttpGetUrl = new Uri("http://127.0.0.1:9999/calculatorservice/metadata");
                    host.Description.Behaviors.Add(behavior);
                }
                host.Opened += delegate { Console.WriteLine("CalculatorService已经启动,按任意键终止服务"); };
                host.Open();
                Console.Read();
            }
        }
    }
}

2.在App.config文件中进行配置

此时可以把Hosting改写为:

using System;
using System.ServiceModel;
using System.ServiceModel.Description;
using Contracts;
using Services;

namespace Hosting
{
    class Program
    {
        static void Main(string[] args)
        {
            using (ServiceHost host = new ServiceHost(typeof(Services.Services)))
            {

                host.Opened += delegate { Console.WriteLine("CalculatorService已经启动,按任意键终止服务"); };
                host.Open();
                Console.Read();
            }
        }
    }
}

App.config

<?xml version="1.0" encoding="utf-8" ?>
  <configuration>
    <system.serviceModel>
      <behaviors>
        <serviceBehaviors>
          <behavior name="metadataBehavior">
            <serviceMetadata httpGetEnabled="true" httpGetUrl="http://127.0.0.1:9999/calculatorservice/metadata"/>
          </behavior>
        </serviceBehaviors>
      </behaviors>
      <services>
        <service behaviorConfiguration="metadataBehavior" name="Services.Services">
          <endpoint address="http://127.0.0.1:9999/calculatorservice" binding="wsHttpBinding" contract="Contracts.ICaculator"/>
        </service>
      </services>
    </system.serviceModel>
  </configuration>

 

服务被成功寄宿后,服务端便开始了服务调用请求的监听工作。此外,服务寄宿将服务描述通过元数据的形式发布出来,相应的客户端就可以获取这些元数据,创建客户端程序进行服务的消费。在VS下,当我们添加服务引用的时候,VS在内部帮我们实现元数据的获取,并借助这些元数据通过代码生成工具(svcutil.exe)自动生成用于服务调用的服务代理相关代码和相应的配置。

下载源码

转载请注明:于哲的博客 » WCF笔记1:metadata