tags:

views:

62

answers:

3

I tried the following code:

 [OperationContract]
 [WebInvoke(UriTemplate="/Users/Register/{user}")]
 void Register(User user);

But when I Try to run this, it tells me the UriTemplate must only contain strings. What if I need to pass in an object to my method as in this case, a User object to my Register method.

If I change the WebInvoke attribute to:

[WebInvoke(UriTemplate="/Users/Register/")]

The browswer displays the error Method not allow when I try to browse to http://localhost:8000/Users/Register for example

A: 

It is exactly as it says. A URI is literally only capable of containing strings. They aren't made for objects. You could probably convert it to take a user name or user id instead if you needed... but you can never use a complex object type as a URI.

md5sum
In this case, I don't have a UserId yet because I need to first create the User.
Xaisoft
I was going to create the user in the Register method. Maybe that is bad design?
Xaisoft
+2  A: 

You are limited to strings in the UriTemplate. You could use multiple parameters to pass multiple strings but you cannot use a complex type. If you want to pass a complex type, then it cannot be anywhere in the URI but rather in the body of a POST/PUT request. The GET request does not take a message body. So your above code could be changed to this:

[OperationContract]
[WebInvoke(Method = "POST", UriTemplate="/Users/Register")]
void Register(User user);

Where you're passing the User object in, not via the Uri, but as part of the POST request.

Steve Michelotti
Thanks, Can you elaborate on what you mean by part of the POST request? I actually tried what you mentioned before, that is just having /Users/Register in my UriTemplate, but then when I navigated to http://localhost:8000/Users/Register, it said Method not allowed.
Xaisoft
What do you mean when you say you "navigated" to the URL? You just hit it in a browser? If so, that did a GET request which is not allowed when you use the [WebInvoke] attribute (you need to use [WebGet] for that). [WebInvoke] is for POST/PUT/DELETE (you'll see I specified "POST") in my code example above. check out: http://www.pluralsight-training.net/microsoft/olt/howtovideos.aspx?category=WCF%20REST
Steve Michelotti
oh duh, you are right about that. The basis of all this is that a user will go to a sign up page, fill in some fields and register. The Register part will be handled by a POST. I can probably handle that on a button click, right? But what is to prevent someone from going to http://localhost:8000/Users/Register?
Xaisoft
A: 

You don't pass objects around as query string parameters (how could you? would it serialize it somehow?) You should pass in the user id.

Kirk Woll
See comments to Steve and md5sum
Xaisoft