我正在尝试向我编写的简单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:
[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#客户端中看到的那样,我已经尝试了applicationType/x-www-form-urlencoded和text/x-json for ContentType,认为它可能与它有关,但它似乎没有.我已经尝试了这个相同服务的GET版本,它工作正常,并返回一个JSON版本的TestData没有问题.但是对于POST,好吧,我现在相当坚持这个:-(
你有没有试过"application/json"而不是"text/x-json".根据此 Stack Overflow问题,应用程序/ json是唯一有效的json媒体类型.