Search code examples
c#httpclient

c# post request using httpparams and headers


I had a client app which was written in angular that post requests to 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 })

Now I have to write this in c#, but stuck with some part

HttpClient httpClient = new HttpClient();  
HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, "http://mysite/connect/token");  
requestMessage.Headers.Add("Content-Type", "application/x-www-form-urlencoded");  

How do I add HttpParams and post request properly please?


Solution

  • Here is the code.

        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);
    

    The above code is just an example to answer the question. But in your implementation, You should use HttpClient static and initialize it at once. Read more