2017-10-12 100 views
-2

我使用Web API 2進行的測試是從AJAX失敗方法返回狀態200。asp.net Web API 2 AJAX失敗

控制器:

[HttpPost] 
    public HttpResponseMessage Post([FromBody] myData m) 
    { 
     return new HttpResponseMessage() 
     { 
      Content = new StringContent("TEST") 
     }; 
    } 

myData的類:

public class myData 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
} 

調用POST從HTML:

<html> 

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

<body> 
    <script> 
     var model = { 
      Name: "Shyju", 
      Id: 123 
     }; 

     $.ajax({ 
     type: "POST", 
     dataType: "text", 
     data: JSON.stringify(model), 
     url: "http://localhost:52884/api/contact", 
     contentType: "application/json", 
     crossDomain: true, 
     success: function (response) { 
      console.log(response) 
     }, 
     error: function (response) { 
      console.log("e : " + response) 
     } 
    }); 
    </script> 
</body> 

</html> 

有誰知道爲什麼它沒有返回消息 「測試」 ?

感謝

+2

它是。使用'res.data'另外,使用'then'而不是'done'。 'done'接受兩個參數,一個解析函數和一個拒絕函數。您正試圖將解析函數視爲數據。參考jQuery文檔。 – Amy

+0

你的意思是我的console.debug中的res.data?但它沒有去完成功能 – user6824563

+0

你在哪裏設置狀態碼不是200? – RandomUs1r

回答

0

拋出一個HTTP異常的Web API 2偉大的方式:

throw new HttpResponseException(
        new HttpResponseMessage 
        { 
         StatusCode = HttpStatusCode.InternalServerError, 
         ReasonPhrase = "Internal Server Error", 
         Content = new StringContent(JsonConvert.SerializeObject(myobject)) 
        }); 

然而,值得注意的是一個簡單的拋出異常的語句導致500,這將做到這一點。在我的例子中,它繞過了錯誤過濾&我的全局異常處理程序,只是返回錯誤狀態代碼和一些錯誤文本到用戶界面。

+0

仍然返回相同的問題。我如何調試Web API? – user6824563