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\"}");