Skip to content

Instantly share code, notes, and snippets.

@zhuqling
Last active December 19, 2015 01:18
Show Gist options
  • Save zhuqling/5874469 to your computer and use it in GitHub Desktop.
Save zhuqling/5874469 to your computer and use it in GitHub Desktop.
WCF REST 当为POST方式+JSON数据类型时,如何传递参数
// 协议定义
[OperationContract]
[WebInvoke
(
// UriTemplate="/EchoWithPost",
// Method="POST", 默认为POST
// BodyStyle = WebMessageBodyStyle.Bare, 默认为Bare无包裹
RequestFormat=WebMessageFormat.Json,
ResponseFormat=WebMessageFormat.Json
)
]
string EchoWithPost(string s);
// 调用
string baseAddress = "http://" + Environment.MachineName + ":4455/Service";
ServiceHost host = new ServiceHost(typeof(Service2), new Uri(baseAddress));
host.AddServiceEndpoint(typeof(Service2), new WebHttpBinding(), "").Behaviors.Add(new WebHttpBehavior());
host.Open();
Console.WriteLine("Host opened");
WebClient c = new WebClient();
// ** 必须设置ContentType = application/json **
c.Headers[HttpRequestHeader.ContentType] = "application/json; charset=utf-8";
c.Encoding = Encoding.UTF8;
// 以POST传递内容,内容为JSON文本
// 当形参为string,则只需传递"XXX"即可,注意必须有双引号
Console.WriteLine(c.UploadString(baseAddress + "/test/", "{\"Number1\":7,\"Number2\":7}"));
Console.Write("Press ENTER to close the host");
Console.ReadLine();
host.Close();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment