纯手写wcf代码,wcf入门,wcf基础教程
1、定义服务协定
=>定义接口
using System.ServiceModel;
namespace WcfConsole
{
/// <summary>
/// 定义服务协定
/// </summary>
[ServiceContract]
interface IW
{
[OperationContract]
string HelloWorld();
}
}
2、实现服务协定
=>实现接口
namespace WcfConsole
{
/// <summary>
/// 实现服务协定
/// </summary>
public class W : IW
{
public string HelloWorld()
{
return "HelloWorld";
}
}
}3、承载和执行服务
=>打开服务
using System;
using System.ServiceModel;
using System.ServiceModel.Description;
namespace WcfConsole
{
/// <summary>
/// 承载和执行主要的 WCF 服务
/// </summary>
class Program
{
static void Main(string[] args)
{
//创建服务网址
Uri url = new Uri("http://localhost:5210/W/");
//创建server主机
ServiceHost host = new ServiceHost(typeof(W), url);
try
{
//加入服务端点
host.AddServiceEndpoint(typeof(IW), new WSHttpBinding(), "serviceName");
//启用元素交换
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
host.Description.Behaviors.Add(smb);
//打开服务
host.Open();
Console.WriteLine("服务打开成功……");
Console.ReadKey();
//关闭服务
host.Close();
}
catch (CommunicationException e)
{
Console.WriteLine(e.Message);
//关闭服务
host.Close();
}
}
}
}
4、创建client
=>须要先打开匃
=>新建项目
=>加入服务引用
5、配置client
=>加入时微软自己主动配置
<?xml version="1.0" encoding="utf-8" ?
> <configuration> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /> </startup> <system.serviceModel> <bindings> <wsHttpBinding> <binding name="WSHttpBinding_IW" /> </wsHttpBinding> </bindings> <client> <!--指定用于调用服务时,端点--> <endpoint address="http://localhost:5210/W/serviceName" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IW" contract="WService.IW" name="WSHttpBinding_IW"> <identity> <userPrincipalName value="DUHUIFENG\liman" /> </identity> </endpoint> </client> </system.serviceModel> </configuration>
6、使用client
=>
using System;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
WService.WClient w = new WService.WClient();
string result = w.HelloWorld();
Console.WriteLine(result);
w.Close();
Console.ReadKey();
}
}
}
浙公网安备 33010602011771号