dsujbhui 发表于 2025-2-7 14:05:53

使用C# 调用deepseek api接口,来实现正常访问

先上图,结果如图
 

 
先去官方网站充值api费用,默认
 
对应的C#代码封装
1public class DeepSeekHelper2 {3      private static readonly HttpClient client = new HttpClient();4      private const string ApiEndpoint = "https://api.deepseek.com/v1/chat/completions";5      private static readonly string apiKey = "你的apikey";6      public static async Task<string> CallDeepSeekAPI(string userQuestion)7    {8          ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;9          try 10          { 11            // 设置请求头 12              client.DefaultRequestHeaders.Clear(); 13            client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}"); 14            client.DefaultRequestHeaders.Add("Accept", "application/json"); 15 16            // 构建请求体 17            var requestBody = new 18              { 19                  model = "deepseek-reasoner", // 根据实际模型调整 20                  messages = new[] 21                { 22                  new 23                { 24                      role = "user", 25                      content = userQuestion 26                } 27              }, 28                  temperature = 0.7 29              }; 30 31            // 序列化请求体 32            //var jsonContent = JsonSerializer.Serialize(requestBody); 33            var jsonContent = JsonConvert.SerializeObject(requestBody); 34            var content = new StringContent(jsonContent, Encoding.UTF8, "application/json"); 35 36            // 发送请求 37            var response = await client.PostAsync(ApiEndpoint, content); 38 39            // 处理响应 40            if (!response.IsSuccessStatusCode) 41              { 42                  throw new Exception($"API请求失败: {response.StatusCode}"); 43              } 44 45            var responseContent = await response.Content.ReadAsStringAsync(); 46            var resultModel = JsonConvert.DeserializeObject<DeepSeekResponse>(responseContent); 47            if (resultModel != null && resultModel.Choices.Count > 0) 48                  return resultModel.Choices[0].Message.Content; 49            return responseContent; 50          } 51          catch (Exception ex) 52          { 53            // 处理异常 54            return $"调用API时发生错误: {ex.Message}"; 55          } 56    } 57 } 58 59 60 61public class DeepSeekResponse 62 { 63      public string Id { get; set; } 64      public string Object { get; set; } 65      public long Created { get; set; } 66      public string Model { get; set; } 67      public List<Choice> Choices { get; set; } 68      public Usage Usage { get; set; } 69      public string SystemFingerprint { get; set; } 70 71      // 重写ToString方法以便更好地显示对象信息 72      public override string ToString() 73    { 74          return $"DeepSeekResponse(Id={Id}, Object={Object}, Created={Created}, Model={Model}, Choices={string.Join(", ", Choices)}, Usage={Usage}, SystemFingerprint={SystemFingerprint})"; 75    } 76 } 77 78public class Choice 79 { 80      public int Index { get; set; } 81      public Message Message { get; set; } 82      // 其他Choice相关的属性... 83 84      // 重写ToString方法以便更好地显示Choice信息(这里仅展示Index和Message作为示例) 85      public override string ToString() 86    { 87          return $"Choice(Index={Index}, Message={Message})"; 88    } 89 } 90 91public class Message 92 { 93      public string Role { get; set; } 94      public string Content { get; set; } 95      // 其他Message相关的属性... 96 } 97 98public class Usage 99 {100      public int PromptTokens { get; set; }101      public int CompletionTokens { get; set; }102      public int TotalTokens { get; set; }103      // 其他Usage相关的属性,包括嵌套的字典等,可以根据需要添加104}
 
调用示例
   private async void SendButton_Click(object sender, RoutedEventArgs e)   {       string requestText = RequestTextBox.Text;       if (!string.IsNullOrWhiteSpace(requestText))       {         try         {                           string responseData = await DeepSeekHelper.CallDeepSeekAPI(requestText); // await new DeepSeekApi().CallDeepSeekAPI(chatRequest);               ResponseTextBox.Text = responseData;         }         catch (Exception ex)         {               ResponseTextBox.Text = $"Error: {ex.Message}";         }       }       else       {         MessageBox.Show("Please enter a request.");       }   }
 
 常见问题:
1 发送请求时出错 InnerException = {"请求被中止: 未能创建 SSL/TLS 安全通道。"}
指定使用TLS1.2加密协议,添加如下代码
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;2 收到内容为空白
服务器繁忙,请把deepseek-chat模型切换到deepseek-reasoner 试试,或者换个时间再次尝试.
模型区别如下.代码中默认使用了reasoner模型,俗称满血版.
默认账户赠送10元余额.

 

 
页: [1]
查看完整版本: 使用C# 调用deepseek api接口,来实现正常访问