user6824563
user6824563

Reputation: 815

asp.net webapi POST works on Postman, but not in browser AJAX request

My asp.net HttpPost test applicantion is working fine in Postman, but it returns error in HTML AJAX request.

My controller:

public class ContactController : ApiController
{
    [HttpPost]
    public string Post([FromBody] myData m)
    {
        return String.Format("Test A");
    }
}

Class:

public class myData
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
}

If I run the request in Postman with the URL: http://localhost:52884/api/contact and the body:

{ 
    "FirstName" : "FName", 
    "LastName" : "LName" 
}

It runs fine! I see the output: "Test A"

However, when I try it with HTML Ajax request:

    <html>

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>

<body>
    <script>
        $.ajax(
        {
            url: "http://localhost:52884/api/contact",
            type: "POST",
            dataType: 'jsonp',
            data: { FirstName: "FName", LastName: "LName" },
            success: function (result) {
                alert(result);
            },
            error: function (xhr, status, p3, p4) {
                console.debug(xhr);
                var err = "Error " + " " + status + " " + p3;
                if (xhr.responseText && xhr.responseText[0] == "{")
                    err = JSON.parse(xhr.responseText).message;
                alert(err);
            }
        });
    </script>
</body>

</html>

I see in the console the error:

The character encoding of the HTML document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the page must be declared in the document or in the transfer protocol
Loading failed for the <script> with source “http://localhost:52884/api/contact?callback=jQuery112409902197956907268_1507917530625&FirstName=FName&LastName=LName&_=1507917530626”.

Upvotes: 0

Views: 1935

Answers (1)

dveloso
dveloso

Reputation: 104

Good night!

You need use JSON.stringfy in your object, against { FirstName: "FName", LastName: "LName"}

See example:

const data = { FirstName: "FName", LastName: "LName"} const jsonData = JSON.stringfy(data);

url: "http://localhost:52884/api/contact", type: "POST", dataType: 'jsonp', data: jsonData, //{ FirstName: "FName", LastName: "LName" }, success: function (result) { alert(result); },

I hope I can help you.

Upvotes: 2

Related Questions