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

先上图,结果如图

 

 

先去官方网站充值api费用,默认

 

对应的C#代码封装

复制代码
复制代码
  1  public class DeepSeekHelper
  2  {
  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 
 61  public 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 
 78  public 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 
 91  public class Message
 92  {
 93      public string Role { get; set; }
 94      public string Content { get; set; }
 95      // 其他Message相关的属性...
 96  }
 97 
 98  public 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元余额.

 

 

 

2025-02-08 14:44:06【出处】:https://www.cnblogs.com/MarsPanda/p/18702486

=======================================================================================

posted on   jack_Meng  阅读(228)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· NetPad:一个.NET开源、跨平台的C#编辑器
历史上的今天:
2014-02-08 横竖两个数字塔的效果BAT批处理怎么写?

导航

< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8
点击右上角即可分享
微信分享提示

喜欢请打赏

扫描二维码打赏

支付宝打赏

主题色彩