5
votes

AJAX request:

$.ajax({
            url: url,
            dataType: 'json',
            type: 'Post',
            data: {token:"4", feed:{"id":0,"message":"Hello World","userId":4} }
        });

Server Side Web API:

 [HttpPost]
 public HttpResponseMessage Post(string token, Feed feed)
 {
    /* Some code */

    return new HttpResponseMessage(HttpStatusCode.Created);
 }

Error Code 404: {"message":"No HTTP resource was found that matches the request URI 'localhost:8080/api/feed'.","messageDetail":"No action was found on the controller 'Feed' that matches the request."}

Why I am getting this error and Why I am not able POST multiple parameters to my API?

5
The parameter names have to match the server routing/mappings. The first parameter typically is id (not token) unless you changed the routing/mapping defaults. - Gone Coding
Is this the correct code? It says you're calling feed, but the method name is post? - Christian Phillips
@TrueBlueAussie localhost:8080/api/feed - Christian Phillips
@christiandev: feed is the controller name, not the method in a WEBAPI call like that. - Gone Coding
Yes Feed is a controller and Post is default action for my webapi - Mohsin JK

5 Answers

13
votes

Start by writing a view model:

public class MyViewModel
{
    public string Token { get; set; }
    public Feed Feed { get; set; }
}

that your controller action will take as parameter:

[HttpPost]
public HttpResponseMessage Post(MyViewModel model)
{
    /* Some code */

    return new HttpResponseMessage(HttpStatusCode.Created);
}

and finally adapt your jQuery call to send it as JSON:

$.ajax({
    url: url,
    type: 'POST',
    contentType: 'application/json',
    data: JSON.stringify({
        token: '4',
        feed: {
            id: 0,
            message: 'Hello World',
            userId: 4
        } 
    })
});

Important things to note for the AJAX call:

  • setting the request contentType to application/json
  • wrapping the data in a JSON.stringify function to effectively convert the javascript object to a JSON string
  • removed the useless dataType: 'json' parameter. jQuery will automatically use the Content-Type response header sent by the server to deduce how to parse the result passed to the success callback.
2
votes

Try this server-side (from memory you can only have a single FromBody parameter so it needs to contain all the incoming properties):

public class TokenAndFeed
{
    public String token {get; set;}
    public Feed feed {get; set;}
}

 public HttpResponseMessage Post([FromBody]TokenAndFeed tokenAndFeed)
 {
    /* Some code */

    return new HttpResponseMessage(HttpStatusCode.Created);
 }
2
votes

I had a similar problem recently and here's some info on how I solved it. I think the problem is to do with how WebApi handles parameters. You can read a bit about it here and here but essentially there are two ways to post parameters, in the body or in the uri. The body can only contain one parameter, but it can be a complex parameter, whereas the uri can contain any number of parameters (up to the uri character limit) but they must be simple. When jquery does a POST ajax call it tries to pass all data parameters in the body, which does not work in your case since the body can only have one parameter.

In code terms I think you need something like this:

var token = "4";
var feed = {Id:0, Message:"Hello World", UserId:4};

$.ajax({
    url: "/api/Feed/?token=" + token,
    dataType: 'json',
    type: 'Post',
    data: JSON.stringify(feed)
});

Hope that helps.

1
votes

Can you post your Feed class, just to make sure the properies match up.

var data = {
     token: "4",
     feed: {Id:0,Message:"Hello World",UserId:4}
}

$.ajax({
            url: "/api/Feed/",
            dataType: 'json',
            type: 'Post',
            data: JSON.stringify(data)
        });
0
votes

Try with this one. You have to get json object data from body. Read Request's input streem and map it to your data model.

public class TokenAndFeed
{
public string Token { get; set; }
public Feed Feed { get; set; }
}      

[HttpPost]
public HttpResponseMessage Post()
{
    System.IO.Stream str;
    String jsonContents;
    Int32 strLen, strRead;
    str = HttpContext.Current.Request.InputStream;
    strLen = Convert.ToInt32(str.Length);
    byte[] byteArray = new byte[strLen];
    strRead = str.Read(byteArray, 0, strLen);
    jsonContents = Encoding.UTF8.GetString(byteArray);

    TokenAndFeed tAndf = JsonConvert.DeserializeObject<TokenAndFeed>(jsonContents);

    // some code here  
    return new HttpResponseMessage(HttpStatusCode.Created);
    }

hope this will help.