Json Format data from console application to service stack

谁说胖子不能爱 提交于 2019-11-28 11:36:31

So if you want to post any untyped and free-text JSON or XML to ServiceStack then you wont be able to ServiceStack's generic typed C# clients (i.e. its JsonServiceClient, XmlServiceClient, etc). Instead you just need to use any basic Http Client like the HttpWebRequest that comes with .NET.

As I've mentioned earlier sending free-text json or xml is not the normal way to call ServiceStack web services (i.e. it's recommended to use typed DTOs and one of the generic service client), but since you've asked here are stand-alone, dependency-free examples of how to call ServiceStack's Hello World example web service:

Sending free-text JSON

const string RemoteUrl = "http://www.servicestack.net/ServiceStack.Hello/servicestack/hello";

var httpReq = (HttpWebRequest)WebRequest.Create(RemoteUrl);
httpReq.Method = "POST";
httpReq.ContentType = httpReq.Accept = "application/json";

using (var stream = httpReq.GetRequestStream())
using (var sw = new StreamWriter(stream))
{
    sw.Write("{\"Name\":\"World!\"}");
}

using (var response = httpReq.GetResponse())
using (var stream = response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
    Assert.That(reader.ReadToEnd(), Is.EqualTo("{\"Result\":\"Hello, World!\"}"));
}

Sending free-text XML

var httpReq = (HttpWebRequest)WebRequest.Create(RemoteUrl);
httpReq.Method = "POST";
httpReq.ContentType = httpReq.Accept = "application/xml";

using (var stream = httpReq.GetRequestStream())
using (var sw = new StreamWriter(stream))
{
    sw.Write("<Hello xmlns=\"http://schemas.servicestack.net/types\"><Name>World!</Name></Hello>");
}

using (var response = httpReq.GetResponse())
using (var stream = response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
    Assert.That(reader.ReadToEnd(), Is.EqualTo("<HelloResponse xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://schemas.servicestack.net/types\"><Result>Hello, World!</Result></HelloResponse>"));
}

I have added the above examples into this Runnable Unit Test.

I recommend getting familiar with a HTTP traffic analyzer tool so you can easily see the HTTP traffic that is sent and received to and from your web service. From then on, being able to workout how to call your service becomes trivial. Some great HTTP traffic analyzers include:

  • Fiddler
  • Network inspectors in Browser (e.g. Chrome, Safari, Firefox and IE have great tools)
  • WireShark
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!