2017-10-12 98 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