1

So this is just a simple example that just pulls in the google homepage information. But what I would like to do is get data from a rest API using HttpClient in C# .NET Framework but the issue is I couldn't figure out how to add in 2 authentication headers, the two parameters should be for like a API-Key and an API-Secret-Key. Here is the code I have right now.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Reporting
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnSubmit_Click(object sender, EventArgs e)
        {
            string StartDate = dtpStartDate.Text;
            string EndDate = dtpEndDate.Text;
            Main();

            async Task Main()
            {
                try
                {
                    var client = new HttpClient();
                    // Call asynchronous network methods in a try/catch block to handle exceptions.
                    HttpResponseMessage response = await client.GetAsync("https://www.google.com");
                    response.EnsureSuccessStatusCode();
                    string responseBody = await response.Content.ReadAsStringAsync();
                    // Above three lines can be replaced with new helper method below
                    // string responseBody = await client.GetStringAsync(uri);
                    label1.Text = responseBody;
                }
                catch (Exception ex)
                {
                    label2.Text = ex.ToString();
                    //throw ex;
                }
            }
        }
    }
}
1
  • Curl is a UNIX/Linux http client library. It has nothing to do with .NET's HTTP client libraries. I've adjusted your terminology for you, so that the question makes sense. Commented Dec 24, 2020 at 8:13

1 Answer 1

2

Can you try the following, please

client.DefaultRequestHeaders.Add("API-Key", "");
client.DefaultRequestHeaders.Add("API-Secret-Key", "");

Note that this does add the headers for the lifetime of the HttpClient

Sign up to request clarification or add additional context in comments.

1 Comment

You can suggest to setup a HttpRequestMessage for temporary HttpRequestMessage.Headers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.