我用下面的方法来发布JSON字符串上面定义的服务,它为我工作:
我的服务:
[WebInvoke(UriTemplate = "TestPost", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
public int Test(string value)
{
Console.Write(value);
return 1;
}
我的客户:
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;
}
我在客户端使用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);
下面是我的小提琴手请求:
POST http://localhost/VDName/AppName/TestPost HTTP/1.1
Content-Type: application/json
Content-Length: 54
Connection: Keep-Alive
"{\"value\":{\"name\":\"value\",\"name1\":\"value\"}}"
的参数是一个字符串,所以它的值应该是一个字符串了。尝试传递'{“值”:“{\”name \“:\”value \“,\”name1 \“:\”value \“}”}'代替。虽然我很惊讶,但服务不会给你一个错误,而不是一个空的参数。 – shambulator 2012-03-15 09:22:04
您可以尝试将BodyStyle移除为WrappedRequest的默认值 – Rajesh 2012-03-15 10:06:01