【问题标题】:Send object through HttpWebRequest (REST Service)通过 HttpWebRequest(REST 服务)发送对象
【发布时间】:2012-10-22 23:40:54
【问题描述】:

我有一个 REST 服务,它接受 PUT 请求的 URL 中的 id。到目前为止,PUT 请求如下所示:

string url = "http://localhost:3596/WidgetManager.svc/Widgets/" + TextBox3.Text;
WebRequest req = WebRequest.Create(url);
req.Method = "PUT";

using (HttpWebResponse resp = req.GetResponse() as HttpWebResponse)
{
    StreamReader reader = new StreamReader(resp.GetResponseStream());
    Label4.Text = reader.ReadToEnd();
} 

但我还需要在我的请求中发送一个 Widget 对象。

Widget w = new Widget();
w.Name = "worked!!!";
w.CogCount = 1000;
w.SprocketSize = 2000;

我看到了很多关于如何发送字符串的例子。但是像这样的对象呢?

【问题讨论】:

    标签: c# rest serializable


    【解决方案1】:

    您可以使用 XML 或 JSON 对其进行序列化。 如果是这么小的对象,你可以编写自己的小方法,如

    .toJSON() {
       return '{"Name":"' + this.name + '", "CogCount":' + this.CogCount + ', "SprocketSize":' + this.SprocketSize + '}';
    }
    //Output: '{"Name":"worked!!!", "CogCount":1000, "SprocketSize":2000}'
    

    另一方面:C# 提供了强大的 (XML) 序列化工具! 这里:http://www.codeproject.com/Articles/1789/Object-Serialization-using-C 只是众多示例之一。

    但如果你使用 PHP 或类似的,JSON 可能会更有趣。

    【讨论】:

      猜你喜欢
      • 2016-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多