使用HttpWebRequest POST和正确映射参数调用WCF WebInvoke方法

时间:2011-11-17 21:57:34

标签: wcf

我已成功将以下WCF合约设置为服务:

[WebInvoke(Method = "POST", UriTemplate = "submit/{apiKey}", ResponseFormat = WebMessageFormat.Xml)]
[OperationContract]
DataServiceResult Submit(string apiKey, string email);

我试图使用HttpWebRequest

来调用它
string url = "http://localhost:51462/Api.svc/web/submit/key";
string formatString = "email=hello@there.com";

byte[] postData = Encoding.ASCII.GetBytes(formatString);

HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "POST";
request.Referer = url;
request.KeepAlive = false;
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postData.Length;

System.IO.Stream outputStream = request.GetRequestStream();
request.AllowAutoRedirect = true;
outputStream.Write(postData, 0, postData.Length);
outputStream.Close();

HttpWebResponse response = request.GetResponse() as HttpWebResponse;
Stream responseStream = response.GetResponseStream();
StreamReader reader = new System.IO.StreamReader(responseStream, Encoding.UTF8);
string srcString = reader.ReadToEnd();

当我运行此代码时,apikey已成功映射。问题是我不知道如何将email参数映射到当前为null的submit方法。

另一个注意事项,在我的应用程序中,我将10-15个参数作为字符串传递,因此向UriTemplate添加电子邮件不是我要找的答案。

1 个答案:

答案 0 :(得分:0)

只是检查,为什么不在URL中传递对象(XML或JSON)?

您可以查看此post以供参考。如果我弄错了,请告诉我。)