繁体   English   中英

如何使用 C# .NET 框架在 HTTP 请求中添加 2 个身份验证标头

[英]How to add 2 authentication headers in a HTTP request using C# .NET Framework

所以这只是一个简单的例子,只是拉入谷歌主页信息。 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 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;
                }
            }
        }
    }
}

请您尝试以下方法

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM