首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >为什么我的C#客户端,POSTing到我的WCF REST服务,返回(400)错误的请求?

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

Stack Overflow用户
提问于 2009-02-22 21:54:48
回答 3查看 27.1K关注 0票数 18

我正在尝试向我编写的一个简单的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,嗯,我现在被困在这个上面了:-(

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/575893

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档