在C#中调用DeepSeek API可以通过多种方式实现,以下是两种常见的方案:使用HttpClient直接发送HTTP请求,或使用第三方库如RestSharp来简化HTTP请求的发送。

方案一:使用 HttpClient 直接发送 HTTP 请求

HttpClient 是 .NET 中用于发送 HTTP 请求和接收 HTTP 响应的类。以下是使用 HttpClient 调用 DeepSeek API 的示例代码:

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

class Program
{
    static async Task Main(string[] args)
    {
        var apiKey = "your_deepseek_api_key";
        var apiUrl = "https://api.deepseek.com/v1/endpoint"; // 替换为实际的API地址

        var client = new HttpClient();
        client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");

        var requestData = new
        {
            prompt = "What is the capital of France?",
            max_tokens = 50
        };

        var json = System.Text.Json.JsonSerializer.Serialize(requestData);
        var content = new StringContent(json, Encoding.UTF8, "application/json");

        var response = await client.PostAsync(apiUrl, content);

        if (response.IsSuccessStatusCode)
        {
            var responseJson = await response.Content.ReadAsStringAsync();
            Console.WriteLine("Response: " + responseJson);
        }
        else
        {
            Console.WriteLine("Error: " + response.StatusCode);
        }
    }
}

方案二:使用 RestSharp 发送 HTTP 请求

RestSharp 是一个流行的第三方库,用于简化 HTTP 请求的发送。以下是使用 RestSharp 调用 DeepSeek API 的示例代码:

  1. 首先,安装 RestSharp NuGet 包:

    dotnet add package RestSharp
    
  2. 然后,使用以下代码调用 DeepSeek API:

using System;
using RestSharp;
using RestSharp.Serializers.Json;
using System.Text.Json;

class Program
{
    static void Main(string[] args)
    {
        var apiKey = "your_deepseek_api_key";
        var apiUrl = "https://api.deepseek.com/v1/endpoint"; // 替换为实际的API地址

        var client = new RestClient(apiUrl);
        client.UseSystemTextJson();

        var request = new RestRequest();
        request.AddHeader("Authorization", $"Bearer {apiKey}");
        request.AddJsonBody(new
        {
            prompt = "What is the capital of France?",
            max_tokens = 50
        });

        var response = client.Post(request);

        if (response.IsSuccessful)
        {
            Console.WriteLine("Response: " + response.Content);
        }
        else
        {
            Console.WriteLine("Error: " + response.StatusCode);
        }
    }
}

总结

  • 方案一:使用 HttpClient 是 .NET 的原生方式,不需要额外的依赖,适合简单的 HTTP 请求。
  • 方案二:使用 RestSharp 可以简化 HTTP 请求的发送和处理,适合需要更多功能和更简洁代码的场景。
Logo

欢迎加入DeepSeek 技术社区。在这里,你可以找到志同道合的朋友,共同探索AI技术的奥秘。

更多推荐