我正在翻譯一個適用于 C#(Xamarin 應用程式)的 javascript 代碼。我從服務器回傳 400 'Bad Request'
我想知道我用 C# 撰寫的代碼是否正確,或者我遺漏了什么。
JS代碼:
function requestTokens(code) {
var codeVerifier = document.getElementById("codeVerifierValue").innerHTML;
var data = {
"grant_type": "authorization_code",
"client_id": "clientid",
"code": code,
"code_verifier": codeVerifier,
"redirect_uri": "https://redirectUrl"
};
$.ajax({
beforeSend: function (request) {
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
},
url: "https://myUrl",
data: data,
success: responseFromPostRequest,
dataType: "json"
});
}
C#代碼:
private HttpClient _httpClient = new HttpClient();
private async Task<string> HttpPost(string url, DataDto data)
{
var jsonData = JsonConvert.SerializeObject(data);
var content = new StringContent(jsonData, Encoding.UTF8, "application/x-www-form-urlencoded");
var response = await _httpClient.PostAsync(new Uri(url), content);
}
謝謝你的幫助
更新日志回應:
{StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Cache-Control: no-store
Connection: keep-alive
Date: Wed, 10 Nov 2021 17:37:43 GMT
Pragma: no-cache
Referrer-Policy: no-referrer
Strict-Transport-Security: max-age=31536000; includeSubDomains
X-Android-Received-Millis: 1636565866035
X-Android-Response-Source: NETWORK 400
X-Android-Selected-Protocol: http/1.1
X-Android-Sent-Millis: 1636565857210
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
Content-Length: 84
Content-Type: application/json
}}
uj5u.com熱心網友回復:
所以我發現在 Content-type application/x-www-form-urlencoded 的情況下,它不應該是粘貼在 post 請求中的 JSON 檔案。
有我發現的代碼:
public static async Task<TResult> PostFormUrlEncoded<TResult>(string url, IEnumerable<KeyValuePair<string, string>> postData)
{
using (var httpClient = new HttpClient())
{
using (var content = new FormUrlEncodedContent(postData))
{
content.Headers.Clear();
content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
HttpResponseMessage response = await httpClient.PostAsync(url, content);
return await response.Content.ReadAsAsync<TResult>();
}
}
}
有了這個它完美地作業
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/361148.html
