我想发送一个POST请求到我写的一个简单的WCF服务,但我一直得到一个400错误的请求。我试图将JSON数据发送到服务。任何人都可以发现我做错了什么吗? :-)为什么我的C#客户端,发布到我的WCF REST服务,返回(400)错误的请求?
这是我的服务接口:
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:
[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,好了,我敢停留在目前这个:-(
你可以提供任何HTTP日志(客户端和/或服务器)? – defeated 2009-02-22 21:59:17