我正在尝试通过HTTP POST调用WCF服务,但该服务返回400错误.我不知道这是由于OperationContract还是我正在进行POST的方式.这就是合同在服务器端的样子:
[OperationContract, WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped)]
Stream Download(string username, int fileid);
Run Code Online (Sandbox Code Playgroud)
以下是我试图通过测试控制台应用程序调用服务的方法:
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();
Run Code Online (Sandbox Code Playgroud)
编辑:我应该说清楚我的目标是测试服务,而不是让它接受原始的HTTP POST.如果有更好的方法可以测试服务,请随时分享.
这是一个非常简单的过程,但不容易访问或直接(不幸的是WCF的许多方面的情况)请查看这篇文章以澄清:
服务合约:
[ServiceContract]
public interface ISampleService
{
[OperationContract]
[WebInvoke(UriTemplate = "invoke")]
void DoWork(Stream input);
}
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
代码背后:
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"];
}
Run Code Online (Sandbox Code Playgroud)