GET

GET单参数

服务器

  1. [OperationContract]
  2. string GetOneParameter(string value);
  3. [WebInvoke(Method = "GET", UriTemplate = "GetOneParameter/{value}", ResponseFormat = WebMessageFormat.Json,
  4. RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
  5. //写在UriTemplate中的参数,必须定义为string类型
  6. public string GetOneParameter(string value)
  7. {
  8. return string.Format("You get: {0}", value);
  9. }

客户端

  1. static string url = "http://localhost:8733/Design_Time_Addresses/WcfServicePractice/Service1/";
  2. public static async void GetOneParameter(int value)
  3. {
  4. HttpClient client = new HttpClient();
  5. var r= await client.GetStringAsync(string.Format("{0}GetOneParameter/{1}",url,value));
  6. }

4种WebMessageBodyStyle

Bare:请求和响应都是裸露的
WrappedRequest:请求是包裹的(,响应是裸露的)
WrappedResponse:响应是包裹的(,请求是裸露的)
Wrapped:请求和响应都是包裹的
例子:GetOneParameter
BodyStyle = WebMessageBodyStyle.Bare / WrappedRequest
返回值:"You get: 1"
BodyStyle = WebMessageBodyStyle.WrappedResponse / Wrapped
返回值:{"GetOneParameterResult":"You get: 1"}
WrappedRequest和Wrapped的请求是包裹的,即要指明key=value

GET多参数

写法1

服务器

  1. [OperationContract]
  2. string GetManyParameter(string number1, string number2);
  3. [WebInvoke(Method = "GET", UriTemplate = "GetManyParameter/{number1}/{number2}", ResponseFormat = WebMessageFormat.Json,
  4. RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
  5. //UriTemplate决定了number1和number2的位置
  6. public string GetManyParameter(string number1, string number2)
  7. {
  8. return string.Format("get : number1 * number2 = "+ (int.Parse(number1)*int.Parse(number2)) );
  9. }

客户端

  1. public static async void GetManyParameter(int number1, int number2)
  2. {
  3. HttpClient client = new HttpClient();
  4. var r = await client.GetStringAsync(url+string.Format("GetManyParameter/{0}/{1}",number1,number2));
  5. }

写法2

服务器

  1. [OperationContract]
  2. string GetManyParameter2(string number1, string number2);
  3. [WebInvoke(Method = "GET", UriTemplate = "GetManyParameter?number1={number1}&number2={number2}", ResponseFormat = WebMessageFormat.Json,RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
  4. //UriTemplate采用key=value的写法
  5. public string GetManyParameter2(string number1, string number2)
  6. {
  7. return string.Format("get : number1 * number2 = " + (int.Parse(number1) * int.Parse(number2)));
  8. }

客户端

  1. public static async void GetManyParameter2(int number1, int number2)
  2. {
  3. HttpClient client = new HttpClient();
  4. var r = await client.GetStringAsync(string.Format("{0}GetManyParameter?number1={1}&number2={2}",url,number1,number2));
  5. }

POST

POST单参数

服务器

  1. [OperationContract]
  2. string PostOneParameter(int value);
  3. [WebInvoke(Method = "POST", UriTemplate = "PostOneParameter", ResponseFormat = WebMessageFormat.Json,RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
  4. public string PostOneParameter(int value)
  5. {
  6. return string.Format("You post: {0}", value);
  7. }

客户端

  1. public static async void PostOneParameter(int value)
  2. {
  3. HttpClient client = new HttpClient();
  4. //"application/json"不能少
  5. HttpContent content = new StringContent(value.ToString(), Encoding.UTF8,"application/json");
  6. var result=await client.PostAsync(url + "PostOneParameter", content);
  7. var r= result.Content.ReadAsStringAsync().Result;
  8. }

POST多参数

服务器

  1. [OperationContract]
  2. string PostManyParameters(int number1, int number2);
  3. [WebInvoke(Method = "POST", UriTemplate = "PostManyParameters", ResponseFormat = WebMessageFormat.Json,RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
  4. //多参数POST必须采用Wrapped/WrappedRequest,指明number1是哪个,number2是哪个
  5. //单参数Bare/Wrapped均可,但是服务器和客户端请求要对应
  6. public string PostManyParameters(int number1,int number2)
  7. {
  8. return string.Format("post : number1 - number2 = " + (number1 - number2));
  9. }

客户端

  1. using Newtonsoft.Json;
  2. using Newtonsoft.Json.Linq;
  3. public static void PostManyParameters(int number1, int number2)
  4. {
  5. WebClient client = new WebClient();
  6. JObject jObject = new JObject();
  7. jObject.Add("number1", number1);
  8. jObject.Add("number2", number2);
  9. client.Headers[HttpRequestHeader.ContentType] = "application/json";
  10. client.Encoding = System.Text.Encoding.UTF8;
  11. string result = client.UploadString(url+ "PostManyParameters", jObject.ToString(Newtonsoft.Json.Formatting.None, null));
  12. }

POST实体类

实体类

  1. using System.Runtime.Serialization;
  2. [DataContract]
  3. public class Student
  4. {
  5. [DataMember]
  6. public int PKID { get; set; }
  7. [DataMember]
  8. public string StudentNumber { get; set; }
  9. [DataMember]
  10. public string Name { get; set; }
  11. }

服务器

  1. [OperationContract]
  2. string PostModel(Student student);
  3. [WebInvoke(Method = "POST", UriTemplate = "PostModel", ResponseFormat = WebMessageFormat.Json,
  4. RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
  5. //客户端手动序列化对象,服务端自动反序列化为类对象
  6. //客户端、服务端类可以不同,只会反序列化回名字相同的字段、属性(忽略大小写)
  7. //实体类加上DataContract和DataMember特性
  8. public string PostModel(Student student)
  9. {
  10. return string.Format("You post a student info: StudentNumber-{0}, Name-{1}", student.StudentNumber, student.Name);
  11. }

客户端

  1. public static async void PostModel(Student student)
  2. {
  3. string str = JsonConvert.SerializeObject(student);
  4. StringContent content = new StringContent(str, Encoding.UTF8, "application/json");
  5. HttpClient client = new HttpClient();
  6. var result =await client.PostAsync(url + "PostModel", content);
  7. var r= result.Content.ReadAsStringAsync().Result;
  8. }

POST实体类和其他参数

服务器

  1. [OperationContract]
  2. string PostModelAndParameter(Student student, string isDelete);
  3. [WebInvoke(Method = "POST", UriTemplate = "PostModelAndParameter/{isDelete}", ResponseFormat = WebMessageFormat.Json,
  4. RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
  5. public string PostModelAndParameter(Student student,string isDelete)
  6. {
  7. if(bool.Parse(isDelete))
  8. {
  9. return string.Format("You want to delete a student, info: StudentNumber-{0}, Name-{1}", student.StudentNumber, student.Name);
  10. }
  11. else
  12. {
  13. return string.Format("You want to add a student, info: StudentNumber-{0}, Name-{1}", student.StudentNumber, student.Name);
  14. }
  15. }

客户端

  1. public static async void PostModelAndParameter(Student student, bool isDelete)
  2. {
  3. string str = JsonConvert.SerializeObject(student);
  4. StringContent content = new StringContent(str, Encoding.UTF8, "application/json");
  5. HttpClient client = new HttpClient();
  6. var result = await client.PostAsync(string.Format("{0}PostModelAndParameter/{1}",url,isDelete), content);
  7. var r = result.Content.ReadAsStringAsync().Result;
  8. }

POST流对象和其他参数

服务器

  1. [OperationContract]
  2. string PostStream(string name, Stream stream);
  3. [WebInvoke(Method = "POST", UriTemplate = "PostStream/{name}", ResponseFormat = WebMessageFormat.Json,
  4. RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
  5. public string PostStream(string name, Stream stream)
  6. {
  7. StreamReader reader = new StreamReader(stream);
  8. string result= string.Format("You post stream : {0} && its name is {1}.", reader.ReadToEnd(), name);
  9. return result;
  10. }

客户端

  1. public static async void PostStream()
  2. {
  3. string name = "123";
  4. Stream stream = new MemoryStream(Encoding.UTF8.GetBytes("This is a stream."));
  5. StreamContent content = new StreamContent(stream);
  6. HttpClient client = new HttpClient();
  7. var result = await client.PostAsync(string.Format("{0}PostStream/{1}",url,name), content);
  8. var r = result.Content.ReadAsStringAsync().Result;
  9. }

返回实体类

服务器

  1. [OperationContract]
  2. Student CombinationStudent(int PKID, string StudentNumber, string Name);
  3. [WebInvoke(Method = "POST", UriTemplate = "CombinationStudent", ResponseFormat = WebMessageFormat.Json,
  4. RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
  5. public Student CombinationStudent(int PKID, string StudentNumber, string Name)
  6. {
  7. Student s = new Student() { PKID = PKID, StudentNumber = StudentNumber, Name = Name };
  8. return s;
  9. }

客户端

  1. public static void CombinationStudent(int PKID, string StudentNumber, string Name)
  2. {
  3. WebClient client = new WebClient();
  4. JObject jObject = new JObject();
  5. jObject.Add("PKID", PKID);
  6. jObject.Add("StudentNumber", StudentNumber);
  7. jObject.Add("Name", Name);
  8. client.Headers[HttpRequestHeader.ContentType] = "application/json";
  9. client.Encoding = System.Text.Encoding.UTF8;
  10. string result = client.UploadString(url + "CombinationStudent", jObject.ToString(Newtonsoft.Json.Formatting.None, null));
  11. Student s = JsonConvert.DeserializeObject<Student>(result);
  12. }

配置文件

  1. <?xml version="1.0" encoding="utf-8" ?>
  2. <configuration>
  3. <appSettings>
  4. <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  5. </appSettings>
  6. <system.web>
  7. <compilation debug="true" />
  8. </system.web>
  9. <!-- 部署服务库项目时,必须将配置文件的内容添加到
  10. 主机的 app.config 文件中。System.Configuration 不支持库的配置文件。 -->
  11. <system.serviceModel>
  12. <services>
  13. <service name="WcfServicePractice.Service1">
  14. <endpoint address="" behaviorConfiguration="webBehavior" binding="webHttpBinding" contract="WcfServicePractice.IService1" />
  15. <host>
  16. <baseAddresses>
  17. <!--如果要修改baseAddress,采用管理员登录运行服务-->
  18. <add baseAddress="http://localhost:8733/Design_Time_Addresses/WcfServicePractice/Service1/" />
  19. </baseAddresses>
  20. </host>
  21. </service>
  22. </services>
  23. <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  24. <behaviors>
  25. <serviceBehaviors>
  26. <behavior>
  27. <serviceMetadata httpGetEnabled="True" />
  28. <serviceDebug includeExceptionDetailInFaults="False" />
  29. </behavior>
  30. </serviceBehaviors>
  31. <endpointBehaviors>
  32. <behavior name="webBehavior">
  33. <webHttp />
  34. </behavior>
  35. </endpointBehaviors>
  36. </behaviors>
  37. </system.serviceModel>
  38. </configuration>

WCF Rest用法的更多相关文章

  1. wcf Svcutil用法

    [转] WCF中可以使用SVCUtil.exe生成客户端代理类和配置文件 1.找到如下地址“C:\Windows\System32\cmd.exe”  命令行工具,右键以管理员身份运行(视系统是否为w ...

  2. WCF SOAP用法

    基本思路 1.新建一个WCF服务库2.在客户端引用处右键,添加服务引用   点击发现,选择目标服务设置好命名空间   可以在高级一栏里面,设置详细信息   点击确认,添加服务引用 3.在客户端自动生成 ...

  3. WCF开发那些需要注意的坑 Z

    执行如下 批处理:"C:\Program Files\Microsoft SDKs\Windows\v6.0A\Bin\svcutil.exe" http://127.0.0.1: ...

  4. 『随笔』WCF开发那些需要注意的坑

    执行如下 批处理:"C:\Program Files\Microsoft SDKs\Windows\v6.0A\Bin\svcutil.exe" http://127.0.0.1: ...

  5. wcf长连接

    项目有用到wcf  大体是jquery + webservice + wcf(网页是客户端,wcf是服务端),现在需要服务端往客户端推送信息,本来是用客户端ajax访问 2秒一次访问服务端,后来觉得这 ...

  6. 那天有个小孩教我WCF[一][1/3]

    那天有个小孩教我WCF[一][1/3] 既然是小孩系列,当然要有一点基础才能快速掌握,归纳,总结的一个系列,哈哈 前言: 第一篇嘛,不细讲,步步教你创建一个简单SOA案例,对WCF有个基本的认识,我不 ...

  7. WCF使用注意事项

    执行如下 批处理:"C:\Program Files\Microsoft SDKs\Windows\v6.0A\Bin\svcutil.exe" http://127.0.0.1: ...

  8. (转)那天有个小孩教我WCF[一][1/3]

    原文地址:http://www.cnblogs.com/AaronYang/p/2950931.html 既然是小孩系列,当然要有一点基础才能快速掌握,归纳,总结的一个系列,哈哈 前言: 第一篇嘛,不 ...

  9. wcf问题集锦

    1.处理程序“svc-Integrated”在其模块列表中有一个错误模块“ManagedPipelineHandler” HTTP 错误 404.3 - Not Found 由于扩展配置问题而无法提供 ...

随机推荐

  1. C# 使用 RabbitMQ

    1. RabbitMQ MQ全称为Message Queue, 消息队列(MQ)是一种应用程序对应用程序的通信方法.应用程序通过写和检索出入列队的针对应用程序的数据(消息)来通信,而无需专用连接来链接 ...

  2. windll对象

    回过头来,再看一下windll和oledll的差别,这两者之间最大的差别是oledll调用的函数都是固定返回HRESULT类型的值,而windll是不固定的类型的.在Python 3.3版本号之前,都 ...

  3. mac nginx php-fpm

    再一次被困在一个傻问题.由于我居然怀疑是不是mac本身就和centos的安装不一样.在一次次地排错后,最终发现.原来是我的nginx.conf的一行配置少写了一个字母.最后多亏用ls检查来定位到这个错 ...

  4. 为什么说 C/C++ 不适合做 Web 开发?(成本高,容易出错,apache等工具分担了大部分工作)

    因为大家在讨论用C#.Java,做出来的项目的时候,用C++的人们还在讨论语言特性 每种语言都有特定适用范围,对应着某类问题.web开发的重头戏不是计算,而是与用户交互和发送sql语句,当然以脚本语言 ...

  5. java基本类型(内置类型)取值范围

    例1: public class PrimitiveTypeTest { public static void main(String[] args) { // byte System.out.pri ...

  6. Android中的动画详解系列【1】——逐帧动画

    逐帧动画其实很简单,下面我们来看一个例子: <?xml version="1.0" encoding="utf-8"?> <animation ...

  7. want cry -- 137,139,445

    通过wireshark抓包发现smb的请求报文,目的端口为445,没有应答报文 之前设置了“阻止连接”导致smb访问被拒绝.修改为要求对连接进行加密 就可以访问

  8. Tools:downloading and Building EDK II工具篇:安装/使用EDKII源代码获取/编译工具[2.3]

    Tools:Installing and using the Required Tools for downloading and Building EDK II工具篇:安装/使用EDKII源代码获取 ...

  9. js如何动态创建表格(两种方法)

    js如何动态创建表格(两种方法) 一.总结 一句话总结: 1.方法一:写好创建表格的html代码,将之赋值给div的innerHTML. 2.方法二.直接用创建好的table元素的方法insertRo ...

  10. [Ramda] Pick and Omit Properties from Objects Using Ramda

    Sometimes you just need a subset of an object. In this lesson, we'll cover how you can accomplish th ...