如何发送包装json请求



你好,我正试图向以下合同发送请求:

[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 Application中发送请求的代码如下:

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时,这是有效的,但现在它是一个wrapperequest。在提琴手我得到错误信息:

"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));

对于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"}

最新更新