Search code examples
c#winformsclientwebapi

How to call a Web API GET method from a .NET client using also token authorization and parameters


I need to call the GET method of a Web API from a Windows Forms application. To call this Web API method, token authorization is needed. The Web API also needs some parameters. Does anyone can help me on how to do this? Thanks in advance


Solution

  • [HttpGet]
        [Route("api/[controller]/name={name}&email={email}phone={phone}&description={description}")]
        public ActionResult<model_class> Get(string name, string email, string phone, string description) {
            
            using (var httpClient = new HttpClient())
            {
                using (var request = new HttpRequestMessage(new HttpMethod("GET"), "https://Endpoint_or_API_URL "))
                {
                    var base64authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes("place_your_toke_here"));
                    request.Headers.TryAddWithoutValidation("Authorization", $"Basic {base64authorization}"); 
    
                    var response = await httpClient.SendAsync(request);
                    
                     HttpContent responseContent = response.Content;
    
                            using (var reader = new StreamReader(await responseContent.ReadAsStreamAsync()))
                            {
                                result = await reader.ReadToEndAsync();
                            }
                }
            }
            }