wcf在post请求时,关于string类型参数传入中文的处理

一、方法默认只有一个参数

(1)BodyStyle = WebMessageBodyStyle.Bare

[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
[Description("地址解析(多个地址以','间隔,解析结果以JSON格式返回)")]
string Parse(string address);

------------------------------------------------------------------------------------

c#代码在客户端调用时,使用以下语句:

//SufeiHttpHelper是一个第三方的http请求调用工具

SufeiHttpHelper helper = new SufeiHttpHelper();
var item = new HttpItem();
item.URL = "http://localhost:35401/parse";
item.ContentType = "application/json";
item.Method = "post";
item.PostEncoding = Encoding.GetEncoding("utf-8");
item.Postdata = "\"天津大学\"";

(2)BodyStyle = WebMessageBodyStyle.Wrapped

[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
[Description("地址解析(多个地址以','间隔,解析结果以JSON格式返回)")]
string Parse(string address);

---------------------------------------------------------------------------------------

item.PostEncoding = Encoding.GetEncoding("utf-8");

item.Postdata = "{\"address\":\"天津\"}";             //包装成json格式,并且指定参数名称

总结:以上两个形式,在传入string参数为中文时,必须要包装成json,如果是数字或字母,在BodyStyle = WebMessageBodyStyle.Bare),可以直接传入,无需包装成json

一、方法有多个参数

[OperationContract]
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped)]
Stream HelloDataStr(String data1,string data2);

由于是多个参数,BodyStyle必须为 WebMessageBodyStyle.Wrapped,否则参数无法映射。

客户端调用:

item.PostEncoding = Encoding.GetEncoding("utf-8");

item.Postdata = {\"data1\":\"hh\",\"data2\":\"ss\"}");

猜你喜欢

转载自www.cnblogs.com/SimpleGIS/p/9938036.html