json WCF WebInvoke 方法 POST

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9715743/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:13:37  来源:igfitidea点击:

WCF WebInvoke Method POST

jsonwcfhttp-post

提问by Armand

I have a wcf service, and I want to test posting data to it. But the parameter of my function never gets any values.

我有一个 wcf 服务,我想测试向它发布数据。但是我的函数的参数永远不会得到任何值。

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

public int Test(string value)  //Value stays null
{
    return 0;
}

The JSON request I send, build using Fiddler2

我发送的 JSON 请求,使用 Fiddler2 构建

http://localhost:49633/Service1.svc/TestPost

User-Agent: Fiddler
Host: localhost:49633
Content-Length: 42
Content-type: application/json

{"value":{"name":"value","name1":"value"}}

I want the parameter to contain a JSON string, so basically I am creating a JSON request that contains a JSON object, because I want to deserialize the JSON object later on into one of my custom objects. Any ideas why the value parameter stays null?

我希望参数包含一个 JSON 字符串,所以基本上我正在创建一个包含 JSON 对象的 JSON 请求,因为我想稍后将 JSON 对象反序列化为我的自定义对象之一。任何想法为什么 value 参数保持为空?

Thanks

谢谢

回答by Rajesh

I am using the below method to post the json string to the service defined above and it works for me:

我使用下面的方法将 json 字符串发布到上面定义的服务,它对我有用:

My service:

我的服务:

[WebInvoke(UriTemplate = "TestPost", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
        public int Test(string value)
        {
            Console.Write(value);
            return 1;
        }

My Client:

我的客户:

private string UseHttpWebApproach(string serviceUrl, string resourceUrl, string method, string requestBody)
        {
            string responseMessage = null;                
            var request = WebRequest.Create(string.Concat(serviceUrl, resourceUrl)) as HttpWebRequest;
            if (request != null)
            {                    
                request.ContentType = "application/json";
                request.Method = method;
            }

            //var objContent = HttpContentExtensions.CreateDataContract(requestBody);
            if(method == "POST" && requestBody != null)
            {                   
                byte[] requestBodyBytes = ToByteArrayUsingJsonContractSer(requestBody);                
                request.ContentLength = requestBodyBytes.Length;
                using (Stream postStream = request.GetRequestStream())
                    postStream.Write(requestBodyBytes, 0, requestBodyBytes.Length);

            }

            if (request != null)
            {
                var response = request.GetResponse() as HttpWebResponse;
                if(response.StatusCode == HttpStatusCode.OK)
                {
                    Stream responseStream = response.GetResponseStream();
                    if (responseStream != null)
                    {
                        var reader = new StreamReader(responseStream);

                        responseMessage = reader.ReadToEnd();
                    }
                }
                else
                {
                    responseMessage = response.StatusDescription;
                }
            }
            return responseMessage;
        }

private static byte[] ToByteArrayUsingJsonContractSer(string requestBody)
        {
            byte[] bytes = null;
            var serializer1 = new DataContractJsonSerializer(typeof(string));
            var ms1 = new MemoryStream();
            serializer1.WriteObject(ms1, requestBody);
            ms1.Position = 0;
            var reader = new StreamReader(ms1);
            bytes = ms1.ToArray();
            return bytes;
        }

My call on the client to the UseHttpWebApproach is as below:

我对客户端对 UseHttpWebApproach 的调用如下:

string serviceBaseUrl = <<your service base url>>;
string resourceUrl = "/TestPost";
string method = "POST";
string jsonText = "{\"value\":{\"name\":\"value\",\"name1\":\"value\"}}";
UseHttpWebApproach(serviceBaseUrl, resourceUrl, method, jsonText);

Below is my Fiddler Request:

以下是我的提琴手请求:

POST http://localhost/VDName/AppName/TestPost HTTP/1.1
Content-Type: application/json
Content-Length: 54
Connection: Keep-Alive

"{\"value\":{\"name\":\"value\",\"name1\":\"value\"}}"