Chuck Savage
Chuck Savage

Reputation: 11955

Consuming Web Service HTTP Post

I'm consuming a web-service with ServiceStack. The header expected is:

POST /SeizureWebService/Service.asmx/SeizureAPILogs HTTP/1.1
Host: host.com
Content-Type: application/x-www-form-urlencoded
Content-Length: length

jsonRequest=string

I'm trying to consume it with this code:

public class JsonCustomClient : JsonServiceClient
{
    public override string Format
    {
        get
        {
            return "x-www-form-urlencoded";
        }
    }

    public override void SerializeToStream(ServiceStack.ServiceHost.IRequestContext requestContext, object request, System.IO.Stream stream)
    {
        string message = "jsonRequest=";
        using (StreamWriter sw = new StreamWriter(stream, Encoding.Unicode))
        {
            sw.Write(message);
        }
        // I get an error that the stream is not writable if I use the above
        base.SerializeToStream(requestContext, request, stream);
    }
}

public static void JsonSS(LogsDTO logs)
{    
    using (var client = new JsonCustomClient())
    {
        var response = client.Post<LogsDTOResponse>(URI + "/SeizureAPILogs", logs);
    }
}

I can't figure out how to add the jsonRequest= before the serialized DTO. How do I do this?

Solution based on Mythz's answer:

Added how I used Mythz's answer for someone having the same issue(s) in the future - enjoy!

public static LogsDTOResponse JsonSS(LogsDTO logs)
{
    string url = string.Format("{0}/SeizureAPILogs", URI);
    string json = JsonSerializer.SerializeToString(logs);
    string data = string.Format("jsonRequest={0}", json);
    var response = url.PostToUrl(data, ContentType.FormUrlEncoded, null);
    return response.FromJson<LogsDTOResponse>();
}

Upvotes: 2

Views: 746

Answers (1)

mythz
mythz

Reputation: 143319

This is a very weird use of a custom service client to send x-www-form-urlencoded data, I think this is a bit ambitious to try as ServiceStack's ServiceClients are meant to send/receive the same Content-type. Where as even though your class is called JsonCustomClient it's no longer a JSON client since you've overrided the the Format property.

The issue your having is likely using the StreamWriter in a using statement which would close the underlying stream. Also I expect you calling the base method to be an error since you're going to have an illegal mix of Url-Encoded + JSON content-type on the wire.

Personally I would steer clear of the ServiceClients and just use any standard HTTP Client, e.g. ServiceStack has some extensions to WebRequest that wraps the usual boilerplate required in making HTTP calls with .NET, e.g:

var json = "{0}/SeizureAPILogs".Fmt(URI)
           .PostToUrl("jsonRequest=string", ContentType.FormUrlEncoded);

var logsDtoResponse = json.FromJson<LogsDTOResponse>();

Upvotes: 3

Related Questions