posts - 710,  comments - 81,  views - 260万
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

GET

GET单参数

服务器

 

1
2
3
4
5
6
7
8
9
10
[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);
}

客户端

1
2
3
4
5
6
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

服务器

1
2
3
4
5
6
7
8
9
10
[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)) );
}

客户端

1
2
3
4
5
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

服务器

1
2
3
4
5
6
7
8
9
[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)));
}

客户端

1
2
3
4
5
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单参数

服务器

1
2
3
4
5
6
7
8
[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);
}

客户端

1
2
3
4
5
6
7
8
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多参数

服务器

1
2
3
4
5
6
7
8
9
10
[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));
}

客户端

1
2
3
4
5
6
7
8
9
10
11
12
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实体类

实体类

1
2
3
4
5
6
7
8
9
10
11
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; }
}

服务器

1
2
3
4
5
6
7
8
9
10
11
12
[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);
}

客户端

1
2
3
4
5
6
7
8
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实体类和其他参数

服务器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
[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);
   }
}

客户端

1
2
3
4
5
6
7
8
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流对象和其他参数

服务器

1
2
3
4
5
6
7
8
9
10
11
[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;
}

客户端

1
2
3
4
5
6
7
8
9
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;
}

返回实体类

服务器

1
2
3
4
5
6
7
8
9
10
[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;
}

客户端

1
2
3
4
5
6
7
8
9
10
11
12
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);
}

配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<?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

posted on   itprobie-菜鸟程序员  阅读(269)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
历史上的今天:
2015-05-28 table 合并行和列
2014-05-28 Developing ADF PageTemplates
点击右上角即可分享
微信分享提示