2016-12-27 27 views
1

我遇到使用REST客戶端的PUT請求問題。我在Postman中嘗試了相同的方法,並且收到了錯誤消息並返回了錯誤消息。所以我期待着在C# - RestSharp Request調用中的相同。相反,我得到一個500內部服務器錯誤,並且request.ErrorException = null和request.ErrorMessage = null。在任何人指責我請求標題之前,我確實設置了request.AddHeader(「Accept」,「application/json」);RestClient - 請求返回500內部服務器錯誤(內容爲html)並且沒有ErrorMessage

我的代碼是這樣

var client = new RestClient(uri); 
var request = new RestRequest(Method.PUT); 
request.AddHeader("Accept", "application/json");` 
request.AddParameter("xx...", value); 
var response = client.Execute(request); 
var content = response.Content; 

所以,現在我看到了response.Content是下面的HTML(我只是張貼信息的部分內容)

<html> 
    <head> 
     <title>Runtime Error</title> 
     <meta name="viewport" content="width=device-width" /> 
     <style> 
     body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;} 
     p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px} 
     b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px} 
     H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red } 
     H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon } 
     pre {font-family:"Consolas","Lucida Console",Monospace;font-size:11pt;margin:0;padding:0.5em;line-height:14pt} 
     .marker {font-weight: bold; color: black;text-decoration: none;} 
     .version {color: gray;} 
     .error {margin-bottom: 10px;} 
     .expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; } 
     @media screen and (max-width: 639px) { 
      pre { width: 440px; overflow: auto; white-space: pre-wrap; word-wrap: break-word; } 
     } 
     @media screen and (max-width: 479px) { 
      pre { width: 280px; } 
     } 
     </style> 
    </head> 

    <body bgcolor="white"> 
..... 

.... 
</html> 

現在在我包裝方法我正在檢查,看StatusCode是不是200,那麼如果request.ErrorException爲null,在這種情況下,只是顯示一個普通的消息'出了什麼事......類型的東西。這只是一個現在的解決方案。我想知道如何獲得確切的錯誤響應或如何處理這種情況。

任何幫助,非常感謝。

回答

0

在Web服務中,實際的錯誤將永遠不會被返回,除非您明確地將錯誤消息設置爲其某個屬性。例如,在WebAPI中,您可以使用Request.CreateResponse()方法返回錯誤消息。該方法需要返回HttpResponseMessage類型。以下是代碼

[HttpPut] 
public HttpResponseMessage MyPutMethod() 
{ 
try 
{ 
...process 
return Request.CreateResponse(HttpStatusCode.OK, "Success"); 
} 
catch (Exception ex) 
{ 
return Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message); 
} 
} 

注意:這是不發送異常細節出於安全原因,一個好主意。

相關問題