2017-10-13 52 views
0

我的asp.net HttpPost测试applicantion在Postman中工作正常,但它在HTML AJAX请求中返回错误。asp.net webapi开机自检邮递员,但没有在浏览器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; } 
} 

如果我运行的URL邮差请求: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”. 
+0

请将**'dataType:'jsonp'' **更改为**'dataType:“json”'**。 –

+0

您正在使用jsonp,但在您的代码中没有回调。您是否尝试过使用'JSON.stringyfy({名字:“FName”,姓氏:“LName”})' – Niladri

+0

您使用的是哪种版本的web api?你有没有在配置文件中设置json格式的默认返回值? – Niladri

回答

1

晚安!

你需要在你的对象使用JSON.stringfy,针对{姓: “FName参数”,名字: “LName的”}

见例如:

常量数据= {姓: “FName参数”,姓氏:“LName”} const jsonData = JSON.stringfy(data);

URL: “http://localhost:52884/api/contact”, 类型: “POST”, 数据类型: 'JSONP', 数据:jsonData,// {姓:其中 “fname”,名字: “LName的”}, 成功:功能(结果){ alert(result); },

我希望我能帮助你。

相关问题