简体   繁体   English

客户端如何将参数传递给RESTful WCF服务

[英]How does the client pass parameter to a RESTful WCF Service

I am building a RESTful service as below with 2 methods (NOTE: I have the ASPNETCompatilibilityMode set to true): 我正在使用以下2种方法构建RESTful服务(注意:我将ASPNETCompatilibilityMode设置为true):

[WebInvoke]
string TestMethodA()
{
        string test = HttpContext.Current.Request.Form["xml"];
}

[WebInvoke]
string TestMethodB(string res)
{
        string xml = res;
}

Now when building the client in order to pass parameter to MethodA i do the following: 现在,在构建客户端以将参数传递给MethodA时,请执行以下操作:

request.AddParameter("xmlString", HttpUtility.HtmlEncode(requestBody));

And for sending message to MethodB i do the following: 为了向MethodB发送消息,请执行以下操作:

request.AddParameter("text/xml",requestBody, ParameterType.RequestBody);

Now the question is: 现在的问题是:

How does the client know on how to pass the parameter? 客户如何知道如何传递参数? The client is not aware of the server implementation. 客户端不知道服务器的实现。

The client that sends the request is using RestSharp Api. 发送请求的客户端正在使用RestSharp Api。

Since MethodB() take a string, WCF has no idea what it should look like. 由于MethodB()采用字符串,因此WCF不知道其外观。 It could be XML, JSON, free text, whatever. 可以是XML,JSON,自由文本等。 In your implementation, you'll just have to document how to format the request and give that to whoever is implementing the client. 在您的实现中,您只需记录如何格式化请求并将其提供给实现客户端的任何人。

A better approach would be to create a C# object, mark it up with appropriate serialization attributes, and use that as the parameter to MethodB(). 更好的方法是创建一个C#对象,用适当的序列化属性对其进行标记,并将其用作MethodB()的参数。 For example: 例如:

[DataContract]
public class MyDataContract{

    [DataMember]
    public string SomeString{get;set;}

    [DataMember]
    public int SomeNumber{get;set;}    
}

public void MethodB(MyDataContract arguments){
  //do stuff

}

This will allow the WCF infrastructure to automatically parse the arguments. 这将允许WCF基础结构自动解析参数。 You can also have WCF autogenerate help documentation from this. 您也可以从中获得WCF自动生成帮助文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM