我正在尝试向我编写的简单 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 版本并且它工作正常,并且返回 TestData 的 JSON 版本没有问题。但是对于 POST,好吧,我现在很困惑 :-(
最佳答案
你试过用“application/json”代替“text/x-json”吗?根据this Stack Overflow 问题 application/json 是唯一有效的 json 媒体类型。
关于c# - 为什么我的 C# 客户端在发布到我的 WCF REST 服务时返回 (400) Bad Request?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/575893/