wcf第1步

添加System.ServiceModel 引用

Wcf 服务端

class Program
{
static void Main(string[] args)
{
ServiceHost host = new ServiceHost(typeof(GreetService), new Uri("http://localhost:20000"));
host.AddServiceEndpoint(typeof (IGreetService), new BasicHttpBinding(), "GreetService");
host.Description.Behaviors.Add(new ServiceMetadataBehavior(){HttpGetEnabled = true});
 
host.Open();
Console.WriteLine("服务已开启");
Console.Read();
}
}

[ServiceContract]
public interface IGreetService
{
[OperationContract]
string Greet(string name);

}

public class GreetService : IGreetService
{

public string Greet(string name)
{
Console.WriteLine(("Hello:"+name));
return "Welcome:" + name;
}
}

 可以使用WcfTestClient.exe来测试Wcf服务

一般在"C:Program Files (x86)Microsoft Visual Studio 12.0Common7IDEWcfTestClient.exe"下面

Wcf客户端

通过添加服务引用 来引用 "http://localhost:20000"的这个服务

然后在Main()里写代码

static void Main(string[] args)
{
GreetService.IGreetService greetService= new GreetServiceClient();
var r= greetService.Greet("abc!");
Console.WriteLine(r);
Console.Read();
}

这里有一个服务引用,如果感觉很不爽的话,可以 以下5步来让他很清爽

1)保存现有的app.config里的内容

2)添加引用->现有项->找到服务引用的文件下面的Reference.cs,对起添加引用

3)将Reference.cs改名,如 GreetService.cs

4)删除服务引用,这时app.config会变化

5)将刚才保存的app.config内容再次粘贴到app.config里

原文地址:https://www.cnblogs.com/zhshlimi/p/5594240.html