【问题标题】:Simple C# API Get Request with Auth credentials?带有身份验证凭据的简单 C# API 获取请求?
【发布时间】:2020-06-09 12:17:52
【问题描述】:

我是 C# 编程的初学者。我有使用 Python 的经验,这基本上是我试图用 C# 复制的内容。

import requests, json

api_user = "userexample@example.com"
api_key = "keyexample"
url = "https://api.example.com/"

response = requests.get(url, auth=(api_user, api_key))
json_response = response.json()

print(json_response)

该代码会是什么样子?谢谢

【问题讨论】:

  • 欢迎来到 StackOverflow!请详细说明您已经在 C# 中尝试过的内容以及为什么它不起作用

标签: python c# asp.net api request


【解决方案1】:

您可以使用HttpClient 库来连接您的 api 服务器。 这是带有 api 基本身份验证的示例代码。 最后请务必致电Dispose(),否则您可能会遇到一些 GC 问题。

public static class Program
    {
        public static async Task Main(string[] args)
        {
            var apiUser = "userexample@example.com";
            var apiKey = "keyexample";
            var url = "https://api.example.com/";

            var client = new HttpClient();
            client.BaseAddress = new Uri("https://api.example.com/");

            var authToken = Encoding.ASCII.GetBytes($"{apiUser}:{apiKey}");
            client.DefaultRequestHeaders.Authorization = 
                new AuthenticationHeaderValue("Basic", Convert.ToBase64String(authToken));
            var response = await client.GetAsync(url);
            var content = response.Content;
            client.Dispose();
        }
    }

【讨论】:

    猜你喜欢
    • 2020-11-09
    • 1970-01-01
    • 2014-12-11
    • 2021-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-21
    • 1970-01-01
    相关资源
    最近更新 更多