简体   繁体   中英

Posting multiple parameters to Web API using jQuery

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:

The Controller

public class UserDTO
{
   public int userID;
   public string username;
}

[HttpPost]
public string Post([FromBody]UserDTO userDTO)
{
   return userDTO.userID.ToString() + " " + userDTO.username;
}

The Web API route config

config.Routes.MapHttpRoute(
   name: "DefaultApi",
   routeTemplate: "api/{controller}/{id}",
   defaults: new { id = RouteParameter.Optional }
);

The jQuery

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 Output

Fiddler shows correctly passed JSON variables and in the Raw view I can see:

{"userID":5,"username":"testuser"}

On Execution

userID = 0
username = null

Help!

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM