使用 WCF RESTful 传递对象 [英] Passing object with WCF RESTful

查看:37
本文介绍了使用 WCF RESTful 传递对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  [WebInvoke(Method = "PUT", UriTemplate = "users/{username}")]
  [OperationContract]
  void PutUser(string username, User newValue);//update a user

我有一个如上所示定义的更新用户方法.然后我使用 HttpWebRequest 来测试该方法,但是如何通过这个 HttpWebResquest 传递 User 对象?以下代码是我目前得到的.

I have a update user method defined as showed above. Then I use a HttpWebRequest to test the method, but how can I pass the User object with this HttpWebResquest? The following code is what I got so far.

     string uri = "http://localhost:8080/userservice/users/userA";
     HttpWebRequest req = WebRequest.Create(uri) as HttpWebRequest;
     req.Method = "PUT";
     req.ContentType = " application/xml";
     req.Proxy = null;

推荐答案

   string uri = "http://localhost:8080/userservice/users/userA";
   string user = "<User xmlns=\"http://schemas.datacontract.org/2004/07/RESTful\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"><DOB>2009-01-18T00:00:00</DOB><Email>userA@example.com</Email><Id>1</Id><Name>Sample  User</Name><Username>userA</Username></User>";
        byte[] reqData = Encoding.UTF8.GetBytes(user);

        HttpWebRequest req = WebRequest.Create(uri) as HttpWebRequest;
        req.Method = "POST";
        req.ContentType = " application/xml";
        req.ContentLength = user.Length;
        req.Proxy = null;
        Stream reqStream = req.GetRequestStream();
        reqStream.Write(reqData, 0, reqData.Length);

        HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
        string code = resp.StatusCode.ToString();

        //StreamReader sr = new StreamReader( resp.GetResponseStream());
        //string respStr = sr.ReadToEnd();
        Console.WriteLine(code);
        Console.Read();

我找到了解决方案,我需要构造我想要传递的xml字符串然后将其写入流

I found the solution, I need to construct the xml string I want to pass and then write it into stream

这篇关于使用 WCF RESTful 传递对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆