【问题标题】:WCF custom datatype as OperationContract parameterWCF 自定义数据类型作为 OperationContract 参数
【发布时间】:2015-02-23 17:56:27
【问题描述】:

我是 WCF 的新手,有一个问题希望您能帮助我。

项目:我被要求创建一个 WCF 服务,允许客户端上传 Word 文件和一些元数据。

客户端没有他们将要进行的 POST 调用的示例,因此我无法从该 WSDL 创建一个类,但该帖子将包含如下数据:

{
    author: 'John Doe',
    pages: '32',
    size: '14432',
    authToken: '322222222233',
    encoding: 'binary'
    name: 'Document1.doc'
}

我正在考虑创建一个 [OperationContract] 例如 bool UploadFile(CustomDocument inputDocument) 而不是 bool UploadFile (string author, string encoding ....) .

我的问题:如果我使用自定义对象作为 [OperationContract] 的输入参数 (CustomDocument),客户端是否能够将所有信息作为字符串传递, int 等在其服务调用中,还是他们必须首先在其末端创建一个 CustomDocument 实例,然后将该对象包含在帖子中?

对不起,我是 WCF 的新手,如果这个问题没有任何意义,我提前道歉;我会根据您的反馈进行更新。

【问题讨论】:

    标签: c# wcf


    【解决方案1】:

    您必须确保 CustomDocument 是 Serializable 对象并具有公共无参数构造函数。 最简单的方法是在 WebService 和将使用它的应用程序之间共享包含类 CustomDocument 的 dll。 但就个人而言,当我尝试将复杂对象发送到 WebServce 时,我更喜欢序列化为字节数组,然后在 WebService 中反序列化。

    祝你好运!

    【讨论】:

    • 谢谢;我会调查这个;但是,我有一种感觉,客户不会对必须序列化感到兴奋。在这种情况下,我将坚持使用多参数方法。再次感谢;我现在有一些阅读要做。
    【解决方案2】:

    您不需要自定义对象CustomDocument。假设你有这个服务

    [ServiceContract]
    public interface IMyTestServce
    {
        [OperationContract]
        [WebInvoke(Method = "POST", 
           BodyStyle = WebMessageBodyStyle.Wrapped,
           UriTemplate = "/Upload?author={author}&pages={pages}&size={size}&name={name}&authToken={authToken}")]
        void Upload(string author, int pages, long size, string name, 
                    string authToken, 
                    Stream file);
    }
    
    public class MyTestService : IMyTestServce
    {
        public void Upload(string author, int pages, long size, string name, 
                           string authToken, 
                           Stream file)
        {
            Console.WriteLine(String.Format("author={0}&pages={1}&size={2}&name={3}&authToken={4}", author, pages, size, name, authToken));
            Console.WriteLine(new StreamReader(file).ReadToEnd());
        }
    }
    

    你可以很容易地这样称呼它

    HttpClient client = new HttpClient();
    var content = new StreamContent(File.OpenRead(filename);
    await client.PostAsync("http://localhost:8088/Upload?author=aa&pages=3&name=bb&authToken=112233", content);
    

    PS:你需要使用webHttpBinding(或者WebServiceHost,如果它不在IIS中)。

    【讨论】:

    • 感谢您的详细回复,并附有示例;我真的很感激它,并发现它非常有用。我会用你的方法来解决我的问题。
    • 快速愚蠢的问题。在您给出的 public void Upload() 示例中,我实际上可以将 int、long 等指定为类型,还是它们都必须是字符串?我只是想知道我是否应该只在方法中指定参数数据类型,还是只接收所有字符串(文件流除外)然后解析/验证以确保其符合要求。
    • @SelfPreservation 我在发布之前测试了上面的代码。有用。说,使用int,long或string,这取决于你。使用任何你喜欢的东西。一切都会奏效。
    猜你喜欢
    • 1970-01-01
    • 2012-02-08
    • 2011-03-31
    • 1970-01-01
    • 1970-01-01
    • 2021-05-02
    • 1970-01-01
    • 1970-01-01
    • 2012-04-21
    相关资源
    最近更新 更多