asp.net webapi POST适用于Postman,但不适用于浏览器AJAX请求

时间:2017-10-13 18:04:43

标签: asp.net ajax asp.net-web-api

我的asp.net HttpPost测试应用程序在Postman中工作正常,但它在HTML AJAX请求中返回错误。

我的控制器:

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

类别:

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

如果我使用网址http://localhost:52884/api/contact和正文:

在邮递员中运行请求
{ 
    "FirstName" : "FName", 
    "LastName" : "LName" 
}

运行良好!我看到输出:“测试A”

但是,当我尝试使用HTML Ajax请求时:

    <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>

我在控制台中看到错误:

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”.

1 个答案:

答案 0 :(得分:1)

晚安!

您需要在对象中使用JSON.stringfy,而不是{FirstName:&#34; FName&#34;,LastName:&#34; LName&#34;}

参见示例:

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

url:&#34; http://localhost:52884/api/contact&#34;,             键入:&#34; POST&#34;,             dataType:&#39; jsonp&#39;,             data:jsonData,// {FirstName:&#34; FName&#34;,LastName:&#34; LName&#34; },             成功:功能(结果){                 警报(结果);             },

我希望我能帮助你。