Json Format data from console application to service stack

前端 未结 1 754
挽巷
挽巷 2020-12-10 20:17

I found you are the only one who answers for service stack, I don\'t have emails and what ever you provided for last questions to me, seems fine.

I have seen your p

相关标签:
1条回答
  • 2020-12-10 20:44

    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
    0 讨论(0)
提交回复
热议问题