要在C#中调用DeepSeek API完成文本生成,需获取API密钥、设置Authorization请求头、构造含messages数组的JSON载荷,并正确解析响应;未认证或载荷错误将导致401/400错误。
☞☞☞AI 智能聊天, 问答助手, AI 智能搜索, 多模态理解力帮你轻松跨越从0到1的创作门槛☜☜☜

要在C#项目中调用DeepSeek API完成文本生成任务,必须先获取有效API密钥、构造符合要求的HTTP请求头与JSON载荷,并正确处理流式或非流式响应。未设置Authorization头或body结构错误会导致401或400错误,无法获得模型输出。
准备基础依赖与认证配置
新建.NET 6+控制台项目,在.csproj中添加System.Net.Http引用(.NET 6+默认包含,无需额外安装)。
声明API密钥和基础地址:【API_KEY必须从https://platform.deepseek.com/api_keys申请,硬编码在代码中仅用于测试,生产环境务必使用环境变量或Secret Manager】
string apiKey = "sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
string baseUrl = "https://api.deepseek.com/v1";
构建并发送标准文本生成请求
第一步:创建HttpClient实例,启用自动重定向并设置默认请求头:
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", apiKey);
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
第二步:构造JSON请求体,注意messages字段必须为数组,且role只能是"system"、"user"或"assistant";content不能为空字符串:
var requestBody = new
{
model = "deepseek-chat",
messages = new[]
{
new { role = "user", content = "你好,请用中文简要介绍你自己" }
},
temperature = 0.7,
max_tokens = 512
};
第三步:序列化并POST到/chat/completions端点:
var json = JsonSerializer.Serialize(requestBody);
统一LLM网关 - 一个API对接70+AI模型,使用单一API密钥即可调用GPT、Claude、Gemini、Qwen、Deepseek、Grok等主流模型。
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PostAsync($"{baseUrl}/chat/completions", content);
第四步:检查状态码,非200需读取错误响应体再抛异常:
if (!response.IsSuccessStatusCode)
{
var errorText = await response.Content.ReadAsStringAsync();
throw new Exception($"API调用失败,状态码:{response.StatusCode},响应:{errorText}");
}
解析返回的JSON响应
方法一:直接反序列化为匿名对象(适合快速验证):
var result = JsonSerializer.Deserialize
string reply = result.choices[0].message.content;
Console.WriteLine(reply);
方法二:定义强类型模型(推荐用于生产):
public record DeepSeekResponse(
string id,
string @object,
long created,
List
public record Choice(Message message);
public record Message(string role, string content);
然后用JsonSerializer.Deserialize
【注意:DeepSeek API返回字段名含@object,C#中需加@前缀或使用JsonPropertyName特性】


















