Zsombor Erdődy-Nagy
Zsombor Erdődy-Nagy

Reputation: 16914

How to invoke RESTful WCF service method with multiple parameters?

I have a RESTful WCF service with a method declared like this:

[OperationContract(Name = "IncrementAge")]
[WebInvoke(UriTemplate = "/", Method = "POST", ResponseFormat = WebMessageFormat.Json)]
Person IncrementAge(Person p);

Here's the implementation:

public Person IncrementAge(Person p)
{
            p.age++;

            return p;
}

So it takes the Person complex type, increments the age property by one, and spits it back, using JSON serialization. I can test the thing by sending a POST message to the service like this:

POST http://localhost:3602/RestService.svc/ HTTP/1.1
Host: localhost:3602
User-Agent: Fiddler
Content-Type: application/json
Content-Length: 51

{"age":25,"firstName":"Hejhaj","surName":"Csuhaj"}

This works. What if I'd like to have a method like this?

Person IncrementAge(Person p, int amount);

So it'd have multiple parameters. How should I construct the POST message for this to work? Is this possible?

Thanks

Upvotes: 2

Views: 12301

Answers (2)

kpozin
kpozin

Reputation: 26939

You should make the message body style wrapped so that you can accept multiple arguments in the POST request body.

Your method signature will be:

[OperationContract(Name = "IncrementAge")]
[WebInvoke(UriTemplate = "/", Method = "POST",
           ResponseFormat = WebMessageFormat.Json,
           BodyStyle = WebMessageBodyStyle.WrappedRequest)]
Person IncrementAge(Person p, int amount);

And the body of the request will look like:

{"p": {"age":25,"firstName":"Hejhaj","surName":"Csuhaj"}, "amount": 1}

The outer JSON object is the anonymous wrapper.

Upvotes: 8

Darrel Miller
Darrel Miller

Reputation: 142014

You could use a query string parameter,

POST /RestService.svc/Incrementor?amount=23
{...}

I think the WCF signature would be:

[OperationContract(Name = "IncrementAge")]
[WebInvoke(UriTemplate = "/?amount={amount}", Method = "POST", ResponseFormat = WebMessageFormat.Json)]
Person IncrementAge(int amount, Person p);

Upvotes: 3

Related Questions