C#调用DeepSeekAPI
时间: 2025-02-08 16:10:37 浏览: 98
### 调用 DeepSeek API 的 C# 实现
为了展示如何在 C# 中调用假设性的 `DeepSeek` API,下面提供了一个基于 HTTP 请求的方式来访问 RESTful Web Service。此方法适用于大多数现代 API 接口。
```csharp
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
public class Program {
private static readonly HttpClient client = new HttpClient();
public static async Task Main() {
var apiKey = "your_api_key_here"; // 用户应替换为自己的API密钥
try {
await CallDeepSeekApiAsync(apiKey);
}
catch (Exception e) {
Console.WriteLine($"请求失败: {e.Message}");
}
Console.ReadLine();
}
private static async Task CallDeepSeekApiAsync(string apiKey) {
string url = $"https://api.deepseek.com/v1/endpoint?apikey={apiKey}";
HttpResponseMessage response = await client.GetAsync(url);
if (!response.IsSuccessStatusCode) {
throw new Exception($"HTTP 错误 ({(int)response.StatusCode}): {await response.Content.ReadAsStringAsync()}");
}
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody); // 输出响应体到控制台
}
}
```
上述代码展示了通过发送 GET 请求给指定 URL 来获取数据的过程[^1]。请注意,在实际应用中应当妥善处理敏感信息如 API 密钥,并考虑异常情况下的错误处理逻辑。
对于更复杂的场景,比如 POST 方法提交 JSON 数据,则可以参照如下方式构建请求:
```csharp
private static async Task PostDataToDeepSeekAsync(string endpointUrl, object dataObject) {
var jsonContent = JsonSerializer.Serialize(dataObject);
HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
HttpResponseMessage postResponse = await client.PostAsync(endpointUrl, content);
if (!postResponse.IsSuccessStatusCode) {
throw new Exception($"POST 请求失败: {(int)postResponse.StatusCode} - {await postResponse.Content.ReadAsStringAsync()}");
}
string resultJson = await postResponse.Content.ReadAsStringAsync();
Console.WriteLine(resultJson);
}
```
这段扩展示例说明了当需要向服务器传递复杂对象时的操作流程[^2]。这里使用了 `System.Text.Json` 命名空间中的序列化工具来进行对象转换。
阅读全文
相关推荐


















