(5)配置完就开始写程序了
1.首先写接口:
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.ServiceModel.Description; using System.ServiceModel.Web; using System.Text; namespace mywcf { // 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码和配置文件中的接口名“IService1”。 [ServiceContract] public interface IService1 { [OperationContract,WebInvoke(Method = "GET",UriTemplate = "hello/{nie}", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] string DoWork(string nie); } }
这个是接口,对外的一种调用(这是服务契约(wcf里面有数据契约,服务契约,消息契约))
[ServiceContract]声明这是一个服务契约
[OperationContract,WebInvoke(Method = "GET",UriTemplate = "hello/{nie}", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]这个是定义接口的访问规则:
Method = "GET"以GET的形式进行访问
UriTemplate = "hello/{nie}"访问的形式:你在浏览器中直接打地址就可以访问的到
例子:http://localhost:23167/Service1.svc/hello/niexinming
"hello/{nie}"必须以指定的名字访问接口,我我指定的名字是hello,当然,这个名字可以随便指定,和函数的名字一样也行
后面的/{nie}是函数的参数,这里的nie必须和函数的参数名一致才行,而且参数只能用string这个类型,参数要以花括号括起来
如果没有参数的话也可以这样写
UriTemplate = "hello" 这样访问就行http://localhost:23167/Service1.svc/hello
或者这样写
UriTemplate = "hello/" 这样访问就行http://localhost:23167/Service1.svc/hello/
BodyStyle = WebMessageBodyStyle.WrappedRequest,WebMessageBodyStyle一个指定是否包装参数和返回值的枚举
WrappedRequest 包装请求,但不包装响应
RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)这个是以json的形式进行响应与请求(其实也可以以xml的形式进行)
string DoWork(string nie);函数
6.
这是实现函数
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.Text; namespace mywcf { // 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码、svc 和配置文件中的类名“Service1”。 // 注意: 为了启动 WCF 测试客户端以测试此服务,请在解决方案资源管理器中选择 Service1.svc 或 Service1.svc.cs,然后开始调试。 public class Service1 : IService1 { public string DoWork(string nie) { return "hello"+nie; } } }
最后的结果是这样的
访问Service1.svc
成功就是这样的
最后成功访问到接口就是这样:
最后还有一点就是如何开启主机的wcf呢?
在 控制面板\所有控制面板项\程序和功能\
win8.1的系统是这样开启的win7还有win service 2008r2呢只要开启.net3.5的wcf再安装.net4.5的升级包就可以用了
生成好的文件直接放进iis 的网站访问目录下就可以运行了
好了,祝大家好运