dotdev
dotdev

Reputation: 573

Creating a webservice to accept file uploads and data

I need to develop a restful web service, that can accept a stream, along with some parameters. From what I have seen and read, a web service that has a Stream input cannot accept any other parameters, yet here is an example showing a working example that accepts a string parameter as well.

I have a web service that looks like so:

[ServiceContract]
public interface ISender
{
    [OperationContract]
    [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    int Upload(Stream fileStream);
}

public int Upload(Stream fileStream)
{
    //this does not parse correctly and provide all of the querystring keys (I dont know why)
    NameValueCollection postParameters = HttpUtility.ParseQueryString(new StreamReader(fileStream).ReadToEnd());

    return 1;
}

But what I really want to do is to be able to accept other string parameters.

THis post, creating a webservice that accepts a file (Stream) doesnt want other params, suggests that when you send a stream it sends everything in the request.

So, for the sake of keeping the post short, I've not mentioned the client. Before attempting to post data to this service, I would like to know whether I am going about this in the right way? Have I setup my web service correctly, and if it is correct that a web service that contains a stream input parameter can only contain a single parameter, how do I obtain access both to the stream, and any other text data I have sent across?

Upvotes: 0

Views: 4386

Answers (1)

user585968
user585968

Reputation:

Answering your first question, you can have more than one parameter but as MSDN states the other parameter bust be in the URI of the request:

The operation that receives the arbitrary data must have a parameter of type Stream. In addition, this parameter must be the only parameter passed in the body of the request. The operation described in this example also takes a filename parameter. This parameter is passed within the URL of the request. You can specify that a parameter is passed within the URL by specifying a UriTemplate in the WebInvokeAttribute. In this case the URI used to call this method ends in “UploadFile/Some-Filename”. The “{filename}” portion of the URI template specifies that the filename parameter for the operation is passed within the URI used to call the operation - How to: Create a Service That Accepts Arbitrary Data using the WCF REST Programming Model

Here is the MSDN example, note the dual parameters and how the filename argument is mapped to the URI:

[ServiceContract]
public interface IReceiveData
{
    [WebInvoke(UriTemplate = "UploadFile/{fileName}")]
    void UploadFile(string fileName, Stream fileContents);
}

Your sample appears to be OK

More Information

Please refer to How to: Create a Service That Accepts Arbitrary Data using the WCF REST Programming Model

Upvotes: 3

Related Questions