我正在尝试向我编写的一个简单的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:
[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的应用程序/x-www-form-urlencoded和text/x-json,认为这可能与此有关,但似乎并非如此。我已经尝试了这个服务的GET版本,它工作得很好,并且返回了TestData的JSON版本,没有任何问题。但是对于POST,嗯,我现在被困在这个上面了:-(
发布于 2009-02-22 22:01:00
您是否尝试过"application/json“而不是"text/x-json”。根据this堆栈溢出问题应用程序/ json是唯一有效的json媒体类型。
发布于 2009-02-22 22:40:22
这里唯一的问题是ContentType。
尝试(推荐)
request.ContentType = "application/json; charset=utf-8";
或者(这也会起作用)
request.ContentType = "text/json; charset=utf-8";
以上两者都解决了这个问题。但是,推荐使用第一种方法,有关JSON-RPC1.1规范的详细信息,请查看http://json-rpc.org
发布于 2009-02-22 21:58:45
尝试:
[OperationContract]
[WebInvoke(
Method = "POST",
UriTemplate = "/create",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
/* non-wrapped */ BodyStyle = WebMessageBodyStyle.Bare )]
String Create(TestData testData);
https://stackoverflow.com/questions/575893
复制相似问题