RokumDev RokumDev - 6 months ago 18
Javascript Question

.Net 5 Web API make jquery POST fails

That's really sucking my brain out, I can't pass data to my POST method in my controller no matter of what try, the issue is passing through a jQuery ajax call, this is my JS code:

$.ajax({
type: "POST",
url: "api/token",
data: {'': 'Hello Web API'},
success: success,
contentType: 'application/json'
});
function success(data) {
console.log("new token response: ")
console.log(data)
}


and this is my server code:

// POST api/Token
[HttpPost("")]
public string Post([FromBody]string accessToken)
{
//var jData = Json.d;
var token = accessToken;
return token;
}


I've documented about with this links: Parameter Binding in ASP.NET Web API, Using jQuery to POST [FromBody] parameters to Web API but nothing works.

Why is so complicated, please any help is welcome.

Answer

According to Asp.Net - section FromBody, you should consider to change your request like this:

        $.ajax({
            type: "POST",
            url: "api/token",
            data: JSON.stringify('Hello Web API'),
            contentType: 'application/json',
            success: success
        });
        function success(data) {
            console.log("new token response: ") 
            console.log(data) 
        }