【发布时间】:2009-02-22 21:54:47
【问题描述】:
我正在尝试向我编写的简单 WCF 服务发送 POST 请求,但我不断收到 400 错误请求。我正在尝试将 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,好吧,我现在对此很困惑:-(
【问题讨论】:
-
你能提供任何http日志(客户端和/或服务器)吗?