2017-04-10 167 views
1

我想在讀取服務器日誌之前弄清楚我能做什麼(日誌記錄,要檢查的內容),因爲我不想在請求之前錯過某些愚蠢的東西。獲取令牌時,HttpClient PostAsync返回500

這裏是我的代碼:

const string URL = "https://SomeURL/api/security/"; 
string urlParameters = string.Format("grant_type=password&username={0}&password={1}", username, password); 
StringContent content = new StringContent(urlParameters, Encoding.UTF8, "application/x-www-form-urlencoded"); 

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11; 

HttpClient client = new HttpClient(); 
client.BaseAddress = new Uri(URL); 
StringContent content = new StringContent(urlParameters, Encoding.UTF8, "application/x-www-form-urlencoded"); 

var tokenResponse = client.PostAsync("token", content).Result; 

我有點新本,所以我不知道接下來要檢查什麼,但使用的郵遞員已經嘗試了相同的請求,並得到與我的令牌,因此它的響應看起來像我錯過了一些東西或者可能格式不正確?

+0

500錯誤是服務器故障,而不是客戶端故障。如果客戶端做錯了,服務器應該返回一個4xx錯誤。因此,請求中可能存在問題,但由於服務器無法正確處理,因此無法知道它是什麼。所以你*有*查看服務器日誌。 –

+0

@ThomasLevesque,我使用郵遞員得到了一個成功的回覆,這就是爲什麼我想我會發布這個問題,看看是否存在我明顯缺少的東西。但是,如果沒有任何人能夠突出顯示,我將不得不像你所說的那樣要求他們。 – Pittfall

+1

嘗試使用'FormUrlEncodedContent'而不是'StringContent':https://gist.github.com/thomaslevesque/8f9f21c7153122a1f509f27ee1fabf80。 –

回答

0

我沒有URL編碼我的參數,這裏的修復(可能是一個更好的方法)。

string urlParameters = string.Format("grant_type=password&username={0}&password={1}", Uri.EscapeDataString(username), Uri.EscapeDataString(password)); 
+0

正如我在我的評論中建議的那樣使用'FormUrlEncodedContent'負責編碼這些值。 –

+0

@ThomasLevesque我確實評論說你的評論是幫助我到達這裏的。我沒有使用FormURLEncodedContent,因爲對象有點笨重。仍然是一個好的解決方 – Pittfall