簡體   English   中英

c# 使用 httpparams 和 headers 發布請求

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM