我從控制器調用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並記錄錯誤 –