2011-12-08 68 views
0

你好我试图发送到以下合同的请求:如何发送包裹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应用程序中的代码如下:

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被设置为裸,但现在它是一个WrappedRequest的原始工作。展望提琴手我得到的错误信息:

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

所以我的问题是你如何包装一个JSON请求?

THE WAY这一轮:

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

回答

0

早报行动,我们不能有查询字符串的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"}