如何使用webinvoke方法(Post或PUT)在wcf rest中传递多个body参数

时间:2011-03-12 07:03:37

标签: wcf parameter-passing webinvoke

我在WCF中编写了一个REST服务,我在其中创建了一个方法(PUT)来更新用户。对于这种方法,我需要传递多个身体参数

[WebInvoke(Method = "PUT", UriTemplate = "users/user",BodyStyle=WebMessageBodyStyle.WrappedRequest)]
[OperationContract]
public bool UpdateUserAccount(User user,int friendUserID)
{
    //do something
    return restult;
}

虽然如果只有一个参数,我可以传递用户类的XML实体。如下:

var myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
myRequest.Method = "PUT";
myRequest.ContentType = "application/xml";
byte[] data = Encoding.UTF8.GetBytes(postData);
myRequest.ContentLength = data.Length;
//add the data to be posted in the request stream
var requestStream = myRequest.GetRequestStream();
requestStream.Write(data, 0, data.Length);
requestStream.Close();

但如何传递另一个参数(friendUserID)值? 任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:12)

对于除GET之外的所有方法类型,只能将一个参数作为数据项发送。所以要么将参数移动到querystring

[WebInvoke(Method = "PUT", UriTemplate = "users/user/{friendUserID}",BodyStyle=WebMessageBodyStyle.WrappedRequest)]
[OperationContract]
public bool UpdateUserAccount(User user, int friendUserID)
{
    //do something
    return restult;
}

或将参数作为节点添加到请求数据

<UpdateUserAccount xmlns="http://tempuri.org/">
    <User>
        ...
    </User>
    <friendUserID>12345</friendUserID>
</UUpdateUserAccount>
相关问题