Search code examples
c#.netasp.net-corehttprequesthttpclient

How to add parameters when using HttpClient to send request .Net Core C#?


How to add parameters when using HttpClient to send request?

I have a problem with my target API; it takes two parameters, and I need to figure out how to add two parameters to my request. Would anyone please explain how I can make that call with HttpClient?

My target API's signature, which I am going to call, looks like:

//It takes post call only
public string Authentication(string UN, string AP)

This is in my startup.cs:

services.AddHttpClient("Authentication", APIHttpClient =>
{
    APIHttpClient.BaseAddress = new Uri("Target API address");
}).ConfigurePrimaryHttpMessageHandler(() =>
    new HttpClientHandler
    {
        UseCookies = false
    }
);

in my class:

public class MyService 
{
   private IHttpClientFactory _clientFactory;

   public MyService(IHttpClientFactory httpClientFactory){
       _clientFactory = httpClientFactory;
   }

   public MyMethod(){

       HttpClient httpClient 
       _httpClientFactory.CreateClient("Authentication");
       
       // I need to add parameter here
   }
}


Hopefully, someone can show me how to code it, Thank you!


Solution

  • You could send request with parameters like below if the api is POST request:

    HttpClient httpClient = _clientFactory.CreateClient("Authentication");
    
    // Create parameters
    var parameters = new Dictionary<string, string>
    {
        { "UN", "aa" },
        { "AP", "bbb" }
    };
    
    // Convert parameters to form-urlencoded content
    var content = new FormUrlEncodedContent(parameters);
    
    // Send POST request
    var response = await httpClient.PostAsync("/auth", content);
    

    The API:

    [HttpPost]
    [Route("/auth")]
    public string Authentication([FromForm]string UN, [FromForm]string AP)
    {
        return UN;
    }
    

    If the api is GET request:

    HttpClient httpClient = _clientFactory.CreateClient("Authentication");
    
    // Create query string with parameters
    var queryString = new StringBuilder();
    queryString.Append("?UN=").Append(Uri.EscapeDataString("aa"));
    queryString.Append("&AP=").Append(Uri.EscapeDataString("bb"));
    
    // Append query string to base URL
    string requestUrl = "/auth" + queryString;
    
    // Send GET request
    var response = await httpClient.GetAsync(requestUrl);