c# - 为什么我的 C# 客户端在发布到我的 WCF REST 服务时返回 (400) Bad Request?

标签 c# wcf rest post

我正在尝试向我编写的简单 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/

相关文章:

c# - Mkbundle 无法在 OS X 上编译 C# 应用程序

.net - 抽象类的所有派生类型的 KnownType?

c# - 常规使用 soap 错误的 WCF 客户端的处置

c# - 通过 WCF 发送大型 Xml 字符串的最有效解决方案?

PHP Curl for Rest API 不起作用

c# - 如何在 Nancy 中编写接受 JSON 的 post 方法以及如何从 C# 客户端调用它?

c# - "Please wait, loading..."文本在 asp.net 页面上的 Page_Load

c# - Acyclic Visitor 相对于 Switch On 类型命令的优势

api - 使用 Backbone Js 和 SLIM 框架进行用户身份验证

c# - MySql 拆分查询组百分比