【问题标题】:How to add 2 authentication headers in a HTTP request using C# .NET Framework如何使用 C# .NET Framework 在 HTTP 请求中添加 2 个身份验证标头
【发布时间】:2020-12-24 05:57:06
【问题描述】:

所以这只是一个简单的例子,它只是拉入谷歌主页信息。但我想做的是在 C# .NET Framework 中使用 HttpClient 从一个 rest API 获取数据,但问题是我不知道如何添加 2 个身份验证标头,这两个参数应该像 API-Key和一个 API-Secret-Key。这是我现在的代码。

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

【问题讨论】:

  • Curl 是一个 UNIX/Linux http 客户端库。它与 .NET 的 HTTP 客户端库无关。我已经为你调整了你的术语,所以这个问题是有意义的。

标签: c# .net httpclient


【解决方案1】:

请你试试下面的方法

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

请注意,这确实会为 HttpClient 的生命周期添加标头

【讨论】:

猜你喜欢
  • 2011-04-28
  • 1970-01-01
  • 2020-03-24
  • 1970-01-01
  • 1970-01-01
  • 2016-03-25
  • 1970-01-01
  • 2020-05-06
  • 1970-01-01
相关资源
最近更新 更多