2017-10-13 41 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); },

我希望我能幫助你。

相關問題