2

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

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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);

2 Comments

Using a query parameter to pass an argument that's acted on in a POST request seems a little strange to me. I'd reserve query parameters for selecting resources (to get or update), rather than for actually modifying the resources.
The problem is that IncrementAge returns a Person, so it is bordering a GET (i.e. Requests a specific representation of a resource). Granted though, that the method is more of an RPC call...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.