GET

GET单参数

服务器

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

客户端

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

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

服务器

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

客户端

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

写法2

服务器

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

客户端

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

POST

POST单参数

服务器

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

客户端

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

POST多参数

服务器

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

客户端

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
public static void PostManyParameters(int number1, int number2)
{
WebClient client = new WebClient();
JObject jObject = new JObject();
jObject.Add("number1", number1);
jObject.Add("number2", number2);
client.Headers[HttpRequestHeader.ContentType] = "application/json";
client.Encoding = System.Text.Encoding.UTF8;
string result = client.UploadString(url+ "PostManyParameters", jObject.ToString(Newtonsoft.Json.Formatting.None, null));
}

POST实体类

实体类

using System.Runtime.Serialization;
[DataContract]
public class Student
{
[DataMember]
public int PKID { get; set; }
[DataMember]
public string StudentNumber { get; set; }
[DataMember]
public string Name { get; set; }
}

服务器

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

客户端

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

POST实体类和其他参数

服务器

[OperationContract]
string PostModelAndParameter(Student student, string isDelete); [WebInvoke(Method = "POST", UriTemplate = "PostModelAndParameter/{isDelete}", ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
public string PostModelAndParameter(Student student,string isDelete)
{
if(bool.Parse(isDelete))
{
return string.Format("You want to delete a student, info: StudentNumber-{0}, Name-{1}", student.StudentNumber, student.Name);
}
else
{
return string.Format("You want to add a student, info: StudentNumber-{0}, Name-{1}", student.StudentNumber, student.Name);
}
}

客户端

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

POST流对象和其他参数

服务器

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

客户端

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

返回实体类

服务器

[OperationContract]
Student CombinationStudent(int PKID, string StudentNumber, string Name); [WebInvoke(Method = "POST", UriTemplate = "CombinationStudent", ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
public Student CombinationStudent(int PKID, string StudentNumber, string Name)
{
Student s = new Student() { PKID = PKID, StudentNumber = StudentNumber, Name = Name };
return s;
}

客户端

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

配置文件

<?xml version="1.0" encoding="utf-8" ?>
<configuration> <appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" />
</system.web>
<!-- 部署服务库项目时,必须将配置文件的内容添加到
主机的 app.config 文件中。System.Configuration 不支持库的配置文件。 -->
<system.serviceModel>
<services>
<service name="WcfServicePractice.Service1">
<endpoint address="" behaviorConfiguration="webBehavior" binding="webHttpBinding" contract="WcfServicePractice.IService1" />
<host>
<baseAddresses>
<!--如果要修改baseAddress,采用管理员登录运行服务-->
<add baseAddress="http://localhost:8733/Design_Time_Addresses/WcfServicePractice/Service1/" />
</baseAddresses>
</host>
</service>
</services>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="True" />
<serviceDebug includeExceptionDetailInFaults="False" />
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="webBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>
</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. boost::any的一般使用方法

    01.#include <iostream>    02.#include <list>    03.#include <boost/any.hpp>    04. ...

  2. oracle 基础表 mysql版

    emp 员工表(empno 员工号/ename 员工姓名/job 工作/mgr 上级编号/hiredate 受雇日期/sal 薪金/comm 佣金/deptno 部门编号) dept 部门表(dept ...

  3. iOS开发之Quzrtz2D 一:认识Quzrtz2D

    一:什么是Quzrtz2D 二:Quzrtz2D实例: 三:图形上下文 四:Quzrtz2D在ios开发中的实际价值 1.什么是Quartz2D? 他是一个二维的绘图引擎,同时支持iOS和Mac系统 ...

  4. 实现上拉加载更多的SwipeRefreshLayout

    转载请标明出处: http://blog.csdn.net/developer_jiangqq/article/details/49992269 本文出自:[江清清的博客] (一).前言: [好消息] ...

  5. iOS QLPreviewController(Quick Look)快速浏览jpg,PDF,world等

    #import <QuickLook/QuickLook.h> @interface ViewController ()<QLPreviewControllerDataSource, ...

  6. [GeekBand] STL Traits 使用简介

    本文参考文献::GeekBand课堂内容,授课老师:张文杰 :C++ Templates  15章节 :网络资料: http://blog.csdn.net/my_business/article/d ...

  7. Android学习--Assets资源文件读取及AssetManager介绍

    APK安装过程        复制APK安装包到data/app目录下,解压并扫描安装包,把dex文件(Dalvik字节码)保存到dalvik-cache目录,并data/data目录下创建对应的应用 ...

  8. 使用readLine()方法遇到的坑

    程序很简单,客户段从控制台读取用户输入,然后发送至服务器端,主要代码如下 服务端代码: 客户端代码: 结果运行的时候,当开启服务端和客户端后,在客户端的控制台 键盘输入 内容,服务端却没有显示内容 原 ...

  9. 音频、视频等文件格式(.ts、.meta)及其认识

    MPEG:Moving Picture Experts Group,动态图像专家组, JPEG:Joint Photographic Experts Group,联合图像专家组 1. .ts .ts ...

  10. textarea随内容自动增加高度

    var autoTextarea = function (elem, extra, maxHeight) { extra = extra || 0; var isFirefox = !!documen ...