[英]c# post request using httpparams and headers
我有一個客戶端應用程序,它是用 angular 編寫的,它發布connect/token
請求
const body = new HttpParams()
.set('username', email)
.set('password', password)
.set('grant_type', "password")
.set('scope', "offline_access");
const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this.http.post<any>(this._baseAuthUrl + 'connect/token', body, { headers })
現在我必須在 c# 中寫這個,但卡住了一些部分
HttpClient httpClient = new HttpClient();
HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, "http://mysite/connect/token");
requestMessage.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
請問如何添加HttpParams
並正確發布請求?
這是代碼。
var httpClient = new HttpClient();
var pairs = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("username", email),
new KeyValuePair<string, string>("password", password),
new KeyValuePair<string, string>("grant_type", "password"),
new KeyValuePair<string, string>("scope", "offline_access")
};
var content = new FormUrlEncodedContent(pairs);
HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, "http://mysite/connect/token");
requestMessage.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
requestMessage.Content = content;
var response = await httpClient.SendAsync(requestMessage);
上面的代碼只是回答問題的一個例子。 但是在您的實現中,您應該使用 HttpClient static 並立即對其進行初始化。 閱讀更多
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.