如何发送包装的json请求

时间:2011-12-08 09:30:22

标签: c# silverlight wcf

您好我正在尝试向以下合同发送请求:

[WebInvoke(Method = "POST", UriTemplate = "UpdateString/{stringlength}?stringid=     {stringid}",BodyStyle = WebMessageBodyStyle.WrappedRequest)]
[Description("Updates String")]
public string UpdateString(long stringid, string stringlength, string newstring)
{
  return code.UpdateString( stringid, stringlength,  newstring);
}

Silverlight应用程序中发送请求的代码如下:

SendNewString = "This is my new string"
public void UpdateString()
{
  WebRequest client = WebRequest.Create(new Uri(_baseUrl));
  client.Method = "POST";
  client.ContentType = HttpContentType;
  client.BeginGetRequestStream(UpdateStringRequestProceed, client);
}

private void UpdateStringRequestProceed(IAsyncResult asynchronousResult)
{
  var request = (HttpWebRequest) asynchronousResult.AsyncState;
  request.Accept = HttpContentType;

  using (Stream requestStream = request.EndGetRequestStream(asynchronousResult))
  {
    using (StreamWriter postDataWriter = new StreamWriter(requestStream))
    {
      DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(object));
                ser.WriteObject(postDataWriter.BaseStream,                                                                           SendNewString);
    }
 }

}

原始这在WebMessageBodyStyle设置为Bare时有效,但现在它是WrappedRequest。看着Fiddler我收到错误信息:

"Message":"OperationFormatter encountered an invalid Message body. Expected to find an     attribute with name 'type' and value 'object'. Found value 'string'."}

所以我的问题是如何包装json请求?

这个方式:

postDataWriter.Write(string.Format("{{\"message\":\"{0}\", \"stringid\":\"{1}\"}}",       SendNewString, stringid));

1 个答案:

答案 0 :(得分:0)

使用POST操作,我们不能将查询字符串作为URI的一部分。为了向上述方法发布请求,请求需要如下所示:

POST  http://localhost/VDName/Service.svc/rest/UpdateString HTTP/1.1
User-Agent: Fiddler
Content-Type: application/json

{"stringid":5, "stringlength":"5","newstring":"5"}