使用编程方式开放元数据端点,有以下几种方法:
1. 使用ServiceMetadataBehavior公开元数据终结点,如下:
using (ServiceHost host = new ServiceHost(typeof(User), new Uri("http://localhost:8000")))
{
var binding = new WSHttpBinding();
host.AddServiceEndpoint(typeof(IUser),
binding,
"user");
ServiceMetadataBehavior metadata = host.Description.Behaviors.Find<ServiceMetadataBehavior>();
if (metadata == null)
{
metadata = new ServiceMetadataBehavior();
host.Description.Behaviors.Add(metadata);
}
metadata.HttpGetUrl = new Uri("http://localhost:8000/mex");
metadata.HttpGetEnabled = true;
host.Open();
Console.WriteLine("Service started, press any key to stop...");
Console.Read();
}
该示例假定存在一个IUser契约和一个User实现。运行程序后,可以在Add Service Reference中使用地址http://localhost:8000/mex来访问元数据。使用https地址开放元数据与使用http相同,不过使用的是HttpsGetUrl属性。
2. 将已有的元数据文件作为一个链接提供给客户使用
做法是使用ServiceMetadataBehavior.ExternalMetadataLocation,该属性是一个Uri类型的属性,用法从略。
3. 公开一个net.tcp端点
static void Main(string[] args)
{
using (ServiceHost host = new ServiceHost(
typeof(User),
new Uri("http://localhost:8000"),
new Uri("net.tcp://localhost:9000")))
{
var binding = new WSHttpBinding();
host.AddServiceEndpoint(
typeof(IUser),
binding,
"user");
ServiceMetadataBehavior metadata = host.Description.Behaviors.Find<ServiceMetadataBehavior>();
if (metadata == null)
{
metadata = new ServiceMetadataBehavior();
host.Description.Behaviors.Add(metadata);
}
metadata.HttpGetEnabled = true;
Binding mexBinding = MetadataExchangeBindings.CreateMexTcpBinding();
host.AddServiceEndpoint(typeof(IMetadataExchange), mexBinding, "mex");
host.Open();
Console.WriteLine("Service started, press any key to stop...");
Console.Read();
}
}
运行如上代码,就可以使用地址net.tcp://localhost:9000/mex来访问元数据了。如果想通过这种方式开放http,https,net.namedpipe类型的地址,代码大同小异,只要看看MetadataExchangeBindings类的定义,就会豁然开朗了。