英文:
How to call HttpPost method using JQuery
问题
I am having a WebAPI.
[HttpPost]
[Route("syncData")]
public async Task
{
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<IHttpActionResult> syncData(MyObject smartNameHere)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论