我从控制器调用Web API的HttpPost方法。对于其他方法,响应是OK和方法效果很好,除了下面提到的方法,指出错误Web API中的内部服务器错误500 MVC4
{StatusCode: 500, ReasonPhrase: 'Internal Server Error', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Pragma: no-cache
Connection: Close
Cache-Control: no-cache
Date: Fri, 16 Aug 2013 09:49:25 GMT
Server: ASP.NET
Server: Development
Server: Server/10.0.0.0
X-AspNet-Version: 4.0.30319
Content-Length: 1855
Content-Type: application/json; charset=utf-8
Expires: -1
}}
我的方法
public int CustomerRegistration(CustomerRequestResponse req)
{
try
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(ConfigurationManager.AppSettings["ServerAddress"].ToString());
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
Uri gizmoUri = null;
var Response = client.PostAsJsonAsync("api/MyAccount/CustomerRegistration", req).Result;
int result = 0;
if (Response.IsSuccessStatusCode)
{
gizmoUri = Response.Headers.Location;
result = Response.Content.ReadAsAsync<Int32>().Result;
}
return result;
}
catch { throw; }
}
我怎么能确定哪里是我的代码中的错误。有什么建议么 ??
编辑:: 追述异常确定 “System.Net.Http.ObjectContent”
{Method: POST, RequestUri: 'http://localhost:56003/api/MyAccount/CustomerRegistration', Version: 1.1, Content: System.Net.Http.ObjectContent`1[[ServiceEntities.MyAccount.CustomerRequestResponse, ServiceEntities, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], Headers:
{
Accept: application/json
Content-Type: application/json; charset=utf-8
Content-Length: 495
}}
任何建议修复它?
EDIT1:
</Message><ExceptionMessage>No MediaTypeFormatter is available to read an object of type 'CustomerRequestResponse' from content with media type 'text/plain'.</ExceptionMessage>
在DEBUG中运行你的API控制器。它应该停在失败的路线上。或者在此方法的顶部设置一个断点并逐步进行,直到出现错误。 –
...对不起 - 我错过了代码中的一个关键点 - 当我想要调试像这样的设置时,我运行两个独立的VS实例 - 一个带有客户端代码,另一个带有API代码。这使得捕获服务器端错误非常容易。您可能还想考虑使用调用堆栈将未处理的exeptions记录到事件日志或无论如何。 –
使用try和catch并记录错误 –