My Web API returns 404 when called from AJAX but works well on PostMan and Swagger.
Post method
// POST api/<controller>
[HttpPost]
public int Post(string url, string RData, string aid, string AuthToken)
{
//do something
}
jQuery AJAX call:
function SaveData() {
var $form = $("#formMain");
var data = Serialize($form);
var RData = JSON.stringify(data);
var Url = window.location.href;
var aid = "12332";
//Get Auth Token
$.ajax({
url: "/api/Register/MyAPIKey", //Getting Auth Token first
type: "GET",
success: function (res) {
let AuthToken = res;
//After receiving Auth token, finally submit the registration data. This throws 404 error only on browser.
$.ajax({
type: "POST",
url: '/api/Register',
data: {
'url': Url,
'RData': RData,
'aid': aid,
'AuthToken': AuthToken
},
success: function (data) {
//Show success message
}
});
}
});
}
The error I get in browser console is:
Message: "No HTTP resource was found that matches the request URI 'http://localhost:54318/api/Register'."
MessageDetail: "No action was found on the controller 'Register' that matches the request."
Postman Screenshot: Please note -1
is expected in response, since some other validation in the API method is incorrect. But we can ignore that for now, since the status is 200
.
The issue was resolved when I replaced the individual parameters in the Post method with an Object having all these as properties.
[HttpPost]
public int Post(PostData Reg)
{
//do something
}
public class PostData
{
public string url { get; set; }
public string RData { get; set; }
public string aid { get; set; }
public string AuthToken { get; set; }
}
And finally setup the dataType in the ajax method as JSON.
dataType: "json"
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.