【.NET实战】调用DeepSeek API实现类官网的智能问答交互
发送
·
一、场景与效果预览
通过.NET 6+开发Web应用,集成DeepSeek大模型API,实现以下效果:
-
用户输入问题后实时获取AI回答
-
对话式UI布局(类似官网)
-
流式响应效果(逐字输出)
-
支持历史对话记录
二、核心实现步骤
1. 准备工作
-
注册DeepSeek开发者账号并获取API Key
-
创建ASP.NET Core Web应用
-
安装NuGet包:
Install-Package System.Net.Http.Json Install-Package Microsoft.Extensions.Http
2. 配置API服务
Program.cs 添加HttpClient服务:
csharp
builder.Services.AddHttpClient("DeepSeek", client => {
client.BaseAddress = new Uri("https://api.deepseek.com/v1/");
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", builder.Configuration["DeepSeek:ApiKey"]);
});
3. 实现问答服务
创建DeepSeekService.cs:
public class DeepSeekService
{
private readonly IHttpClientFactory _httpClientFactory;
public DeepSeekService(IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
}
public async Task<string> GetAnswerAsync(string question)
{
var client = _httpClientFactory.CreateClient("DeepSeek");
var request = new {
model = "deepseek-chat",
messages = new[] {
new { role = "user", content = question }
},
stream = true
};
var response = await client.PostAsJsonAsync("chat/completions", request);
response.EnsureSuccessStatusCode();
// 使用IAsyncEnumerable实现流式读取
await using var stream = await response.Content.ReadAsStreamAsync();
using var reader = new StreamReader(stream);
StringBuilder result = new();
while (!reader.EndOfStream)
{
var line = await reader.ReadLineAsync();
if (!string.IsNullOrEmpty(line))
{
var data = JsonSerializer.Deserialize<JsonElement>(line);
if (data.TryGetProperty("choices", out var choices))
{
var content = choices[0].GetProperty("delta").GetProperty("content").GetString();
result.Append(content);
yield return content; // 实现逐字返回
}
}
}
}
}
4. 前端交互实现
Index.cshtml 对话界面:
html
<div class="chat-container">
<div id="chatHistory" class="messages">
<!-- 历史消息 -->
</div>
<div class="input-area">
<input type="text" id="txtQuestion" placeholder="输入您的问题..." />
<button οnclick="askQuestion()">发送</button>
</div>
</div>
<script>
function askQuestion() {
const question = document.getElementById('txtQuestion').value;
const chatHistory = document.getElementById('chatHistory');
// 添加用户消息
chatHistory.innerHTML += `
<div class="message user-message">
<div class="avatar">👤</div>
<div class="content">${question}</div>
</div>`;
// 建立SSE连接
const eventSource = new EventSource(`/api/chat?question=${encodeURIComponent(question)}`);
let answerDiv = document.createElement('div');
eventSource.onmessage = (e) => {
answerDiv.textContent += e.data;
window.scrollTo(0, document.body.scrollHeight);
};
eventSource.onerror = () => {
eventSource.close();
answerDiv.textContent += "\n[对话结束]";
};
}
</script>
运行 HTML
5. 流式响应API接口
ChatController.cs:
csharp
[ApiController]
[Route("api/[controller]")]
public class ChatController : Controller
{
private readonly DeepSeekService _service;
public ChatController(DeepSeekService service)
{
_service = service;
}
[HttpGet]
public async Task ChatStream(string question)
{
Response.ContentType = "text/event-stream";
await foreach (var chunk in _service.GetAnswerAsync(question))
{
await Response.WriteAsync($"data: {chunk}\n\n");
await Response.Body.FlushAsync();
await Task.Delay(50); // 模拟逐字输出效果
}
Response.Close();
}
}
三、关键优化点
-
安全增强:通过
[Authorize]添加身份验证 -
上下文管理:使用Redis缓存历史对话
-
性能优化:配置HttpClient Polly重试策略
-
样式优化:CSS添加打字机动画效果
完整代码已开源至Github:[示例仓库链接]
注意事项:
-
实际API参数请参考[DeepSeek官方文档]
-
生产环境需添加速率限制和错误处理
-
建议使用CancellationToken实现请求中止
更多推荐


所有评论(0)