我正在尝试向我编写的简单WCF服务发送POST请求,但我一直收到400 Bad Request的错误。我试图向服务发送JSON数据。是否有人能发现我的问题所在?:-)
这是我的服务接口:
public interface Itestservice
{
[OperationContract]
[WebInvoke(
Method = "POST",
UriTemplate = "/create",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
String Create(TestData testData);
}
具体实现:
public class testservice: Itestservice
{
public String Create(TestData testData)
{
return "Hello, your test data is " + testData.SomeData;
}
}
数据合同:
[DataContract]
public class TestData
{
[DataMember]
public String SomeData { get; set; }
}
最后是我的客户端代码:
private static void TestCreatePost()
{
Console.WriteLine("testservice.svc/create POST:");
Console.WriteLine("-----------------------");
Uri address = new Uri("http://localhost:" + PORT + "/testweb/testservice.svc/create");
// Create the web request
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
// Set type to POST
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
//request.ContentType = "text/x-json";
// Create the data we want to send
string data = "{\"SomeData\":\"someTestData\"}";
// Create a byte array of the data we want to send
byte[] byteData = UTF8Encoding.UTF8.GetBytes(data);
// Set the content length in the request headers
request.ContentLength = byteData.Length;
// Write data
using (Stream postStream = request.GetRequestStream())
{
postStream.Write(byteData, 0, byteData.Length);
}
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
// Console application output
Console.WriteLine(reader.ReadToEnd());
}
Console.WriteLine();
Console.WriteLine();
}
请问有人能想出我哪里做错了吗?如您所见,在C#客户端中,我尝试了ContentType的application/x-www-form-urlencoded和text/x-json两种类型,以为这可能与问题有关,但似乎并不是这样。我已经尝试了一个相同服务的GET版本,它可以正常工作并返回JSON格式的TestData,但对于POST请求,目前我卡住了 :-(