如何使用 JQuery 调用 HttpPost 方法

huangapple go评论83阅读模式
英文:

How to call HttpPost method using JQuery

问题

I am having a WebAPI.

[HttpPost]
[Route("syncData")]
public async Task 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?

英文:

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?

答案1

得分: 2

这是因为.NET找不到与您提供的有效负载匹配的POST路由。您正在将对象传递给操作,但操作期望参数。

您需要将控制器操作的参数转换为一个具有您需要的三个字段的对象,例如:

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

然后在控制器操作本身中 -

public async Task<IHttpActionResult> syncData(MyObject smartNameHere)
英文:

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&lt;IHttpActionResult&gt; syncData(MyObject smartNameHere)

huangapple
  • 本文由 发表于 2020年1月6日 21:51:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/59613322.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定