【问题标题】:WCF JSON POST request, single string parameter not binding and returning 400WCF JSON POST 请求,单个字符串参数未绑定并返回 400
【发布时间】:2015-06-04 20:41:27
【问题描述】:

在我的 WCF(天蓝色云)服务中,我想支持 JSON。我正在创建一些测试方法来查看是否一切正常。我可以让 GET 调用正常工作,但是当我使用简单参数进行 POST 时,我总是会得到:

The remote server returned an error: (400) Bad Request.

如果我不发送参数,它会执行该方法,但参数当然是空值。我尝试了不同格式的 JSON 和 WebMessageBodyStyle,但似乎都不起作用。

如果我将参数类型更改为 Stream 我会收到数据,但我必须手动反序列化它。这不应该是必要的吧?

界面:

        [OperationContract]
        [WebInvoke(UriTemplate = "Test",
            Method = "POST", 
            BodyStyle = WebMessageBodyStyle.WrappedRequest,
            RequestFormat = WebMessageFormat.Json,
            ResponseFormat = WebMessageFormat.Json)]
        string Test(string data);

实施:

        public string Test(string data)
        {           
            return "result is " + data;
        } 

测试客户端:

            WebClient client = new WebClient();
            client.Headers["Content-type"] = "application/json";
            client.Encoding = System.Text.Encoding.UTF8;
            string jsonInput = "{'data':'testvalue'}";
            string postResponse = client.UploadString(postUrl, jsonInput);
            Console.WriteLine("post response: " + postResponse);

【问题讨论】:

    标签: c# .net json wcf rest


    【解决方案1】:

    黄金组合是在 JSON 代码中使用双引号并结合 WebMessageBodyStyle.WrappedRequest。

    工作 JSON:

       string jsonInput = "{\"data\":\"testvalue\"}";
    

    将 WebMessageBodyStyle 设置为 Bare 时,以下 JSON 有效:

       string jsonInput = "\"testvalue\"";
    

    【讨论】:

    • 非常感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多