1:首先新建一个解决方案
2:右击解决方案添加一个控制台程序
3:对着新建好的控制台程序右击添加wcf服务
最后的结果:
有3个文件 app.config Iwcf_server.cs wcf_server.cs 一个配置文件 一个接口类 一个继承接口的文件。
代码:
Iwcf_server.cs
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.Text; namespace w_sp { // 注意: 如果更改此处的接口名称 "Iwcf_server",也必须更新 App.config 中对 "Iwcf_server" 的引用。 [ServiceContract] public interface Iwcf_server { [OperationContract] string t_sp(string measage); } }
wcf_server.cs
代码:
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.Text; namespace w_sp { // 注意: 如果更改此处的类名 "wcf_server",也必须更新 App.config 中对 "wcf_server" 的引用。 public class wcf_server : Iwcf_server { public string t_sp(string message) { return string.Format("我想你了{0}",message); } } }
注意:wcf_server.cs 继承Iwcf_server.cs后必须全部实现接口定义的方法。并且不能实例化接口 实现接口的方法也不能用静态static 修饰(如public static string t_sp 错误)。
Program.cs
代码:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ServiceModel; namespace w_sp { class Program { static void Main(string[] args) { using (ServiceHost host = new ServiceHost(typeof(w_sp.wcf_server))) { host.Open(); Console.ReadLine(); host.Close(); } } } }
最后一个就是app.config文件的配置
<add baseAddress="http://localhost:8731/Design_Time_Addresses/w_sp/wcf_server/" /> 默认是这个样子 ,可以简化成http://localhost:8731/wcf_server/。
最后编译生成下项目可以了 ,这里一个wcf程序完成了。
最后运行w_sp.exe文件
----------------------------------------------------------------------------------------------------- 分割线 -------------------------------------------------------------------------------------------
按照上面的步骤继续添加一个客户端控制台程序,最后添加服务引用
地址(url)就是配置文件里面的
最后在第2个新建的cs文件的代码:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using w_p.tsp; namespace w_p { class w_sp { static void Main(string[] args) { tsp.Iwcf_serverClient sp = new Iwcf_serverClient(); string str = sp.t_sp("苏培"); Console.WriteLine(str); Console.ReadLine(); } } }
运行结果:
遇到的问题:
1:添加引用服务的时候(当然要输入正确的地址否则也提示无效)
我们可以理解我们写的wcf是一个远程的服务你添加引用它,肯定要运行这个服务(好比连接数据库肯定要首先打开数据库服务)
2:运行结果的时候
原理和上面的一样。