WCF Rest用法
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用法的更多相关文章
- wcf Svcutil用法
[转] WCF中可以使用SVCUtil.exe生成客户端代理类和配置文件 1.找到如下地址“C:\Windows\System32\cmd.exe” 命令行工具,右键以管理员身份运行(视系统是否为w ...
- WCF SOAP用法
基本思路 1.新建一个WCF服务库2.在客户端引用处右键,添加服务引用 点击发现,选择目标服务设置好命名空间 可以在高级一栏里面,设置详细信息 点击确认,添加服务引用 3.在客户端自动生成 ...
- WCF开发那些需要注意的坑 Z
执行如下 批处理:"C:\Program Files\Microsoft SDKs\Windows\v6.0A\Bin\svcutil.exe" http://127.0.0.1: ...
- 『随笔』WCF开发那些需要注意的坑
执行如下 批处理:"C:\Program Files\Microsoft SDKs\Windows\v6.0A\Bin\svcutil.exe" http://127.0.0.1: ...
- wcf长连接
项目有用到wcf 大体是jquery + webservice + wcf(网页是客户端,wcf是服务端),现在需要服务端往客户端推送信息,本来是用客户端ajax访问 2秒一次访问服务端,后来觉得这 ...
- 那天有个小孩教我WCF[一][1/3]
那天有个小孩教我WCF[一][1/3] 既然是小孩系列,当然要有一点基础才能快速掌握,归纳,总结的一个系列,哈哈 前言: 第一篇嘛,不细讲,步步教你创建一个简单SOA案例,对WCF有个基本的认识,我不 ...
- WCF使用注意事项
执行如下 批处理:"C:\Program Files\Microsoft SDKs\Windows\v6.0A\Bin\svcutil.exe" http://127.0.0.1: ...
- (转)那天有个小孩教我WCF[一][1/3]
原文地址:http://www.cnblogs.com/AaronYang/p/2950931.html 既然是小孩系列,当然要有一点基础才能快速掌握,归纳,总结的一个系列,哈哈 前言: 第一篇嘛,不 ...
- wcf问题集锦
1.处理程序“svc-Integrated”在其模块列表中有一个错误模块“ManagedPipelineHandler” HTTP 错误 404.3 - Not Found 由于扩展配置问题而无法提供 ...
随机推荐
- C# 使用 RabbitMQ
1. RabbitMQ MQ全称为Message Queue, 消息队列(MQ)是一种应用程序对应用程序的通信方法.应用程序通过写和检索出入列队的针对应用程序的数据(消息)来通信,而无需专用连接来链接 ...
- windll对象
回过头来,再看一下windll和oledll的差别,这两者之间最大的差别是oledll调用的函数都是固定返回HRESULT类型的值,而windll是不固定的类型的.在Python 3.3版本号之前,都 ...
- mac nginx php-fpm
再一次被困在一个傻问题.由于我居然怀疑是不是mac本身就和centos的安装不一样.在一次次地排错后,最终发现.原来是我的nginx.conf的一行配置少写了一个字母.最后多亏用ls检查来定位到这个错 ...
- 为什么说 C/C++ 不适合做 Web 开发?(成本高,容易出错,apache等工具分担了大部分工作)
因为大家在讨论用C#.Java,做出来的项目的时候,用C++的人们还在讨论语言特性 每种语言都有特定适用范围,对应着某类问题.web开发的重头戏不是计算,而是与用户交互和发送sql语句,当然以脚本语言 ...
- java基本类型(内置类型)取值范围
例1: public class PrimitiveTypeTest { public static void main(String[] args) { // byte System.out.pri ...
- Android中的动画详解系列【1】——逐帧动画
逐帧动画其实很简单,下面我们来看一个例子: <?xml version="1.0" encoding="utf-8"?> <animation ...
- want cry -- 137,139,445
通过wireshark抓包发现smb的请求报文,目的端口为445,没有应答报文 之前设置了“阻止连接”导致smb访问被拒绝.修改为要求对连接进行加密 就可以访问
- Tools:downloading and Building EDK II工具篇:安装/使用EDKII源代码获取/编译工具[2.3]
Tools:Installing and using the Required Tools for downloading and Building EDK II工具篇:安装/使用EDKII源代码获取 ...
- js如何动态创建表格(两种方法)
js如何动态创建表格(两种方法) 一.总结 一句话总结: 1.方法一:写好创建表格的html代码,将之赋值给div的innerHTML. 2.方法二.直接用创建好的table元素的方法insertRo ...
- [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 ...