HTTP POST to a WCF service
本文关键字:WCF service to POST HTTP | 更新日期: 2023-09-27 18:07:57
我试图通过HTTP POST调用WCF服务,但该服务返回400错误。我不知道这是否由于OperationContract或我正在做POST的方式。这是合约在服务器端的样子:
[OperationContract, WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped)]
Stream Download(string username, int fileid);
下面是我如何通过测试控制台应用程序调用服务:
HttpWebRequest webRequest = WebRequest.Create("http://localhost:8000/File/Download") as
HttpWebRequest;
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
byte[] bytes = Encoding.ASCII.GetBytes("username=test&fileid=1");
Stream os = null;
webRequest.ContentLength = bytes.Length;
os = webRequest.GetRequestStream();
os.Write(bytes, 0, bytes.Length);
os.Close();
WebResponse webResponse = webRequest.GetResponse();
我应该说清楚,我的目标是测试服务,而不是让它接受原始的HTTP post。如果我有更好的方法来测试服务,请随时分享。
这是一个相当简单的过程,但不是很容易访问或直接(不幸的是,WCF的许多方面都是如此),请查看这篇文章来澄清:
服务合同:
[ServiceContract]
public interface ISampleService
{
[OperationContract]
[WebInvoke(UriTemplate = "invoke")]
void DoWork(Stream input);
}
HTML源代码:
<form method="post" action="Service.svc/invoke">
<label for="firstName">First Name</label>: <input type="text" name="firstName" value="" />
<br /><br />
<label for="lastName">Last Name</label>: <input type="text" name="lastName" value="" />
<p><input type="submit" /></p>
</form>
背后的代码:
public void DoWork(Stream input)
{
StreamReader sr = new StreamReader(input);
string s = sr.ReadToEnd();
sr.Dispose();
NameValueCollection qs = HttpUtility.ParseQueryString(s);
string firstName = qs["firstName"];
string lastName = qs["lastName"];
}
如果您可以使用其他内容类型,您可以使用json代替,这将在您的示例中工作。
改变webRequest.ContentType = "application/x-www-form-urlencoded";
byte[] bytes = Encoding.ASCII.GetBytes("username=test&fileid=1");
webRequest.ContentType = "application/json";
byte[] bytes = Encoding.ASCII.GetBytes("{'"username'":'"test'",'"fileid'":1");
如果你必须使用application/x-www-form-urlencoded内容类型,谷歌wcf application/x-www-form-urlencoded的几个帖子和其他SO问题描述的解决方案。