2013-08-16 88 views
-2

我從控制器調用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> 
+1

在DEBUG中運行你的API控制器。它應該停在失敗的路線上。或者在此方法的頂部設置一個斷點並逐步進行,直到出現錯誤。 –

+1

...對不起 - 我錯過了代碼中的一個關鍵點 - 當我想要調試像這樣的設置時,我運行兩個獨立的VS實例 - 一個帶有客戶端代碼,另一個帶有API代碼。這使得捕獲服務器端錯誤非常容易。您可能還想考慮使用調用堆棧將未處理的exeptions記錄到事件日誌或無論如何。 –

+0

使用try和catch並記錄錯誤 –

回答

2

我會做的第一件事是驗證客戶端是做請求是正確的 - 正確的網址,標題,正文。爲此,您可以在應用程序中啓用fiddler作爲代理。本欄目添加到您Web.config,並嘗試與小提琴手再次打開運行代碼 - 現在你應該可以看到提琴手請求:

<system.net> 
    <defaultProxy> 
    <proxy proxyaddress="http://127.0.0.1:8888" />  
    </defaultProxy> 
</system.net> 

如果請求是好的,檢查服務器你要連接它實際上已經啓動並正在運行,並且它以正確的標題爲您提供了正確的響應。

我懷疑它應該足以確定問題。

順便說一句:在現實生活中,你的catch塊實際上有用嗎?爲了使它比現在更有用,你可以添加一些log4net日誌記錄,這可能也有助於識別未來的問題。

0

我認爲在處理MyAccountController的CustomerRegistration操作數據時存在一個錯誤。如果在進行過程中發生錯誤,我寧願您檢查您的控制器。

0

如果您有標準DLL(後端)和Web腳本(前端:如ashx或aspx等)設置,那麼很容易忘記上傳(到服務器)對Web腳本所做的更改。 我收到了這樣的錯誤,但是當我確認我的所有代碼/腳本都處於同步狀態並上傳到服務器時,它就消失了。