Asp.Net Core Web Api - HttpClient usage

Cenk 1,036 Reputation points
2022-12-19T08:32:48.8+00:00

Hi there,

I am upgrading my legacy asp.net web API 2 to Core 6. In my legacy application, I was calling a third-party web service as follows. It says it is obsolete and use HttpClient. How to convert this to HttpClient? Which HttpClient consumption pattern should I use? (are-you-using-httpclient-in-the-right-way) I was reading some settings from Web config, so should I read them from appsettings.json?

Thank you.

public static class EzPinApiCaller  
    {  
          
        public static async Task<HttpResponseMessage?> CallToken(string url)  
        {  
              
            //HTTPWebRequest DEV  
            var request = (HttpWebRequest)WebRequest.Create(WebConfigurationManager.AppSettings["EzPinService"] + url);  
  
            request.ContentType = "application/x-www-form-urlencoded";  
            request.Method = "POST";  
            request.KeepAlive = false;  
  
            //Create a list of your parameters  
            var postParams = new List<KeyValuePair<string, string>>(){  
                new KeyValuePair<string, string>("client_id", WebConfigurationManager.AppSettings["ClientId"]) ,  
                new KeyValuePair<string, string>("secret_key", WebConfigurationManager.AppSettings["Secret"])  
            };  
            var keyValueContent = postParams;  
            var formUrlEncodedContent = new FormUrlEncodedContent(keyValueContent);  
            var urlEncodedString = await formUrlEncodedContent.ReadAsStringAsync();  
  
            using (var streamWriter = new StreamWriter(await request.GetRequestStreamAsync()))  
            {  
                await streamWriter.WriteAsync(urlEncodedString);  
            }  
  
            var httpResponse = (HttpWebResponse)(await request.GetResponseAsync());  
  
            var response = new HttpResponseMessage  
            {  
                StatusCode = httpResponse.StatusCode,  
                Content = new StreamContent(httpResponse.GetResponseStream()),  
            };  
  
            return response;  
        }  
  
        public static async Task<HttpResponseMessage> CallOrder(string url, string token, WatsonOrderRequest watsonOrderRequest)  
        {  
            HttpResponseMessage response = null;  
            try  
            {  
                //HTTPWebRequest DEV  
                var request = (HttpWebRequest)WebRequest.Create(WebConfigurationManager.AppSettings["EzPinService"] + url);  
  
                request.ContentType = "application/x-www-form-urlencoded";  
                request.Method = "POST";  
                request.KeepAlive = false;  
                request.Headers.Add("Authorization", "Bearer " + token);  
  
                //Create a list of your parameters  
                var postParams = new List<KeyValuePair<string, string>>(){  
                    new KeyValuePair<string, string>("sku", watsonOrderRequest.sku.ToString()) ,  
                    new KeyValuePair<string, string>("quantity", watsonOrderRequest.quantity.ToString()),  
                    new KeyValuePair<string, string>("pre_order", watsonOrderRequest.pre_order.ToString()),  
                    new KeyValuePair<string, string>("price", watsonOrderRequest.price),  
                    new KeyValuePair<string, string>("reference_code", watsonOrderRequest.reference_code.ToString())  
                };  
  
                var keyValueContent = postParams;  
                var formUrlEncodedContent = new FormUrlEncodedContent(keyValueContent);  
                var urlEncodedString = await formUrlEncodedContent.ReadAsStringAsync();  
  
                using (var streamWriter = new StreamWriter(await request.GetRequestStreamAsync()))  
                {  
                    await streamWriter.WriteAsync(urlEncodedString);  
                }  
  
                var httpResponse = (HttpWebResponse)(await request.GetResponseAsync());  
                response = new HttpResponseMessage  
                {  
                    StatusCode = httpResponse.StatusCode,  
                    Content = new StreamContent(httpResponse.GetResponseStream()),  
                };  
            }  
            catch (WebException ex)  
            {  
                //Identify EZPIN error details  
                var resp = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();  
                dynamic obj = JsonConvert.DeserializeObject(resp);  
                var detail = obj.detail;  
                var code = obj.code;  
                response = new HttpResponseMessage(HttpStatusCode.BadRequest) { Content = new StringContent(detail.ToString(), System.Text.Encoding.UTF8, "application/json") };  
            }  
  
  
            return response;  
        }  
  
        public static async Task<HttpResponseMessage> CallCards(string url, string token)  
        {  
            HttpResponseMessage response = null;  
  
            //HTTPWebRequest DEV  
            var request = (HttpWebRequest)WebRequest.Create(WebConfigurationManager.AppSettings["EzPinService"] + url);  
  
            request.ContentType = "application/x-www-form-urlencoded";  
            request.Method = "GET";  
            request.KeepAlive = false;  
            request.Headers.Add("Authorization", "Bearer " + token);  
  
  
            var httpResponse = (HttpWebResponse)(await request.GetResponseAsync());  
            response = new HttpResponseMessage  
            {  
                StatusCode = httpResponse.StatusCode,  
                Content = new StreamContent(httpResponse.GetResponseStream()),  
            };  
  
            return response;  
        }  
    }  
Developer technologies ASP.NET ASP.NET Core
{count} votes

1 answer

Sort by: Most helpful
  1. AgaveJoe 30,126 Reputation points
    2022-12-19T12:01:27.183+00:00

    How to convert this to HttpClient?

    The first step is to make an effort to learn the HttpClient features. This can be accomplished by reading the official documentation which contains example code. Seasoned developers read the documentation and create a simple test application when working with a unfamiliar library.

    HttpClient Class

    Which HttpClient consumption pattern should I use?

    You have not explained what "consumption patterns" you are referring to. In my experience, the standard programming pattern is openly discussed in the official documentation. Essentially, the HttpClient is configured at application startup and dependency injection is used in the constructors.

    Make HTTP requests with the HttpClient class

    I was reading some settings from Web config, so should I read them from appsettings.json?

    Correct. The appsettings.json is one of the configuration locations in .NET. The official documentation covers configuration. I use server variables. Read the documentation to pick a configuration approach that suits your needs.

    Configuration in ASP.NET Core

    You have a lot of experience in these forums. Please make an effort to design and write code. If you run into trouble when post the code, explain the problem, and explain the expected results.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.