WCF Rest用法
Posted guohu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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>
转载地址:https://www.jianshu.com/p/4d71da8c183f
以上是关于WCF Rest用法的主要内容,如果未能解决你的问题,请参考以下文章
在 WCF REST 服务 POST 方法中处理 Json 请求数据
WCF Rest WebFaultException 总是返回 202
从 IParameterInspector AfterCall 可以处理的 WCF Rest 服务返回带有消息的 HttpStatus 代码