Sriram Tamilarasan
Sriram Tamilarasan

Reputation: 521

How to call HttpPost method using JQuery

I am having a WebAPI.

  [HttpPost]
    [Route("syncData")]
    public async Task<IHttpActionResult> syncData(string webUrl, string Title, string Id)
    {
        try
        {
            ...
         }
      }

trying to call this API using JQuery,

var settings = {
"url": "https://localhost:44370/api/SPHome/syncData",
"method": "POST",
"timeout": 0,
"Content-Type": "application/json",
"data": JSON.stringify({
  "webUrl": "Url",
  "Title": "Test",
  "Id": "Sample"
})
};

$.ajax(settings).done(function (response) {
 console.log(response);
 });

If i pass all three parameters in querysting it is hitting my API but when i pass the data in body content i am getting Status Code: 404

May I know what i am missing in this?

Upvotes: 0

Views: 154

Answers (1)

dunnel123
dunnel123

Reputation: 392

This happens because .NET cannot find a POST route that matches the payload you have given it. You're passing an object to an action but the action expects parameters.

You'll want to turn the parameters for your controller action into an object that has the three fields you need, e.g.

public class MyObject
{
  public string WebUrl {get;set;}
  public string Id {get;set;}
  public string Title {get;set;}
}

Then in the controller action itself -

public async Task<IHttpActionResult> syncData(MyObject smartNameHere)

Upvotes: 2

Related Questions