下边是不引用web服务来调用 WCF 服务示例
WCF程序分为三个部分:服务、宿主和客户端。下面就一步一步按这三个部分来构建一个简单的WCF程序。可以选择这三个部分都创建独立的解决方案,也可以在一个解决方案中创建三个项目。在下面的例子中将采用将三个项目放在一个解决方案中。服务使用类库项目,宿主和客户端使用控制台程序。
首先:
首先
我们建一个类库来写服务
Contracts
Test 为一个控制台程序 当做服务寄宿的宿主
Client 模拟客户端
具体代码如下.
1.建一个类库 写下边两个类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
namespace Contracts
{
[ServiceContract(Name = "CarRentalService", Namespace = "http://www.artech.com/")]
public interface IcarRentalService
{
[OperationContract]
string sayhello();
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Contracts
{
public class CarRentalService : IcarRentalService
{
#region IcarRentalService 成员
public string sayhello()
{
return "Say hello";
}
#endregion
}
}
2.写一个控制台程序,让服务来寄宿。
这里写法有两种
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using Contracts;
using System.ServiceModel.Description;
namespace Test
{
class Program
{
static void Main(string[] args)
{
#region
using (ServiceHost host1 = new ServiceHost(typeof(CarRentalService)))
{
host1.AddServiceEndpoint(typeof(IcarRentalService), new WSHttpBinding(), "http://127.0.0.1:9999/b/a");
if (host1.Description.Behaviors.Find<ServiceMetadataBehavior>() == null)
{
ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
behavior.HttpGetEnabled = true;
behavior.HttpGetUrl = new Uri("http://127.0.0.1:9999/b/a");
host1.Description.Behaviors.Add(behavior);
}
host1.Opened += delegate
{
Console.WriteLine("服务已经启动");
};
host1.Open();
Console.ReadKey();
}
#endregion
//下边为这次程序中的所用实力.
using (ServiceHost host = new ServiceHost(typeof(CarRentalService)))
{
host.AddServiceEndpoint(typeof(IcarRentalService), new BasicHttpBinding(),
new Uri("http://localhost:10000/a/b"));
if (host.State != CommunicationState.Opening)
host.Open();
Console.WriteLine("服务已经启动!");
Console.ReadLine();
}
}
}
}
3,下来,我们来调用这个简单的WCF服务。
新建一个控制台程序,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using Contracts;
namespace Client
{
class Program
{
static void Main(string[] args)
{
EndpointAddress ea =
new EndpointAddress("http://localhost:10000/a/b");
IcarRentalService proxy =
ChannelFactory<IcarRentalService>.CreateChannel(new BasicHttpBinding(), ea);
Console.WriteLine(proxy.sayhello());
Console.ReadLine();
}
}
}
由此得出WCF服务具有全局性.