Question

I need to call the following REST API

[OperationContract]
[WebInvoke(Method = "POST",
UriTemplate = "/{subscriptionId}/servers?op=ChangeSubscription")]
Stream ChangeAllServersSubscription(string subscriptionId, Stream requestStream);

How can I create and pass Stream requestStream? The stream will contain JSON formatted string

Was it helpful?

Solution

Before making use of any kind of Stream, you should ask the API supplier which stream he's expecting to receive.

Here's an example using a MemoryStream, after you create your JSON:

// Random objects, just to make the code clear
var myObject = new {Name = "Yakov"};
var myId = "1";
var myJson = JsonConvert.SerializeObject(myObject);

// Create a MemoryStream (Encoding should be as needed)
var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(myJson));

// Call your code
var responseStream = ChangeAllServersSubscription(myId, memoryStream);

// And dispose the MemoryStream after you're done.
memoryStream.Dispose();

OTHER TIPS

You can create a HttpWebRequest on the client side, set the url to point to your service, set appropriate method- in your case POST. For example:

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://server/id/servers?op=ChangeSubscription");
request.Method = "POST";

Then use GetRequestStream() to get the stream on the client side, write your json into this stream, close the stream, then execute the request by calling GetResponse().

    Stream stream= request.GetRequestStream();
    //stream.Write write contents of your file here!
    stream.Close();
    HttpWebResponse response= (HttpWebResponse)request.GetResponse();
    //process the response from server

If everything went right your web service will get hit and receive your file.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top