You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python转C#:带身份验证的API Get请求实现(C#初学者求助)

Translating Authenticated Python GET Request to C#

Hey there! Since you already have Python experience, making this switch to C# should be straightforward once you get familiar with .NET's HttpClient and JSON handling. Here's a direct equivalent of your Python code, with explanations to map each part to what you know:

Required Namespaces

First, make sure you include these at the top of your C# file—they're the .NET equivalents of Python's requests and json modules:

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Threading.Tasks;

Full C# Code

This replicates your Python script's functionality, including basic authentication and JSON parsing:

class Program
{
    static async Task Main(string[] args)
    {
        // Your credentials and API URL (matches your Python variables)
        string apiUser = "userexample@example.com";
        string apiKey = "keyexample";
        string url = "https://api.example.com/";

        // Initialize HttpClient (reuse this instance instead of creating new ones!)
        using HttpClient client = new HttpClient();

        // Add Basic Authentication header (equivalent to requests' auth=(user, key))
        string credentials = $"{apiUser}:{apiKey}";
        byte[] credentialsBytes = System.Text.Encoding.ASCII.GetBytes(credentials);
        string base64Credentials = Convert.ToBase64String(credentialsBytes);
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", base64Credentials);

        try
        {
            // Send GET request (async/await is standard in C# for I/O operations)
            HttpResponseMessage response = await client.GetAsync(url);
            
            // Ensure the request succeeded (throws an error if status code is 4xx/5xx)
            response.EnsureSuccessStatusCode();

            // Read and parse JSON response (equivalent to response.json())
            string jsonContent = await response.Content.ReadAsStringAsync();
            var jsonResponse = JsonSerializer.Deserialize<object>(jsonContent);

            // Print the parsed JSON in a readable format
            Console.WriteLine(JsonSerializer.Serialize(jsonResponse, new JsonSerializerOptions { WriteIndented = true }));
        }
        catch (HttpRequestException ex)
        {
            Console.WriteLine($"Request failed: {ex.Message}");
        }
    }
}

Key Mapping to Your Python Code

Let's break down how this matches what you wrote in Python:

  • requests.get(url, auth=(api_user, api_key)) → client.GetAsync(url) with the Authorization header set manually. C#'s HttpClient doesn't have a direct auth parameter, so we construct the Basic Auth header ourselves (this is exactly what requests does under the hood).
  • response.json() → JsonSerializer.Deserialize<object>(jsonContent). We first read the response content as a string, then deserialize it into a generic object. If you work with a specific JSON structure later, you can replace object with a custom class for better type safety.
  • print(json_response) → We serialize the parsed object back to a formatted string (the WriteIndented = true option makes it pretty-printed, just like Python's default JSON output).

Quick Notes

  • Always reuse HttpClient instances instead of creating new ones each time—this avoids socket exhaustion issues in longer-running applications.
  • The async/await pattern is standard in C# for asynchronous operations like HTTP requests (it keeps your app responsive while waiting for the API response).
  • If you're using an older .NET framework (pre-.NET Core 3.0), you might need to use Newtonsoft.Json (Json.NET) instead of System.Text.Json—just replace the deserialization line with JsonConvert.DeserializeObject(jsonContent).

内容的提问来源于stack exchange,提问作者Avery Delanfield

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 22:12:37