为什么我的C#客户端,POST到我的WCF REST服务,返回(400)错误请求?

时间:2009-02-22 21:54:48

标签: c# wcf rest post

我正在尝试向我写的简单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,好吧,我现在非常坚持这个: - (

3 个答案:

答案 0 :(得分:8)

您是否尝试过“application / json”而不是“text / x-json”。根据{{​​3}} Stack Overflow问题应用程序/ json是唯一有效的json媒体类型。

答案 1 :(得分:4)

这里唯一的问题是ContentType。

尝试(推荐)

request.ContentType = "application/json; charset=utf-8";

或(这也会起作用)

request.ContentType = "text/json; charset=utf-8";

以上两点都解决了这个问题。但是,建议使用第一个,有关JSON-RPC 1.1规范的详细信息,请查看http://json-rpc.org

答案 2 :(得分:0)

尝试:

[OperationContract]
[WebInvoke(
  Method = "POST",
  UriTemplate = "/create",
  RequestFormat = WebMessageFormat.Json,
  ResponseFormat = WebMessageFormat.Json,
  /* non-wrapped */ BodyStyle = WebMessageBodyStyle.Bare )]
String Create(TestData testData);