Reputation: 448
Like many before me, I'm trying to pass multiple parameters to a Web API project. I've tried several solutions offered on this site with no luck. My latest failing iteration looks as follows:
public class UserDTO
{
public int userID;
public string username;
}
[HttpPost]
public string Post([FromBody]UserDTO userDTO)
{
return userDTO.userID.ToString() + " " + userDTO.username;
}
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var apiUrl = "http://localhost:55051/api/User/Post";
var userDTO = {
userID: 5,
username: "testuser"
};
$.ajax({
type: "POST",
url: apiUrl,
data: JSON.stringify(userDTO),
datatype: "json",
contenttype: "application/json; charset=utf-8"
)};
Fiddler shows correctly passed JSON variables and in the Raw view I can see:
{"userID":5,"username":"testuser"}
userID = 0
username = null
I figure that the issue is with Web API and it's difficulty in working with JSON parameters given that my POST appears to be correctly formatted in Fiddler. Any ideas?
Upvotes: 5
Views: 5587
Reputation:
Doesn't your jQuery ajax call fail? Check for it?
var apiUrl = "http://localhost:55051/api/UserController/Post";
Seeing your code this should probably be:
var apiUrl = "http://localhost:55051/api/User";
The word controller is typically not part of your URL. You don't have to explicitly invoke POST, it should pick it by convention since your ajax call is a POST.
EDIT:
The above and your casing in your ajax call as commented.
I personally use Firebug (a Firefox extension) to debug cases like these. If find it more convenient than fiddler in this case.
Upvotes: 2
Reputation: 906
My guess is you have to pass: { userDTO : { userID ... } } as data in jquery. The request is wrapped. You have to stringify this of course.
Right now you pass parameters but none of them match userDTO so it gets default values.
See my previous answer here: Jquery post
Upvotes: 1