本文将指导您如何使用Blazor框架和DeepSeek API构建一个简单的聊天应用。Blazor是一个用于构建交互式Web UI的框架,它允许开发者使用C#编写前端代码。DeepSeek API则提供强大的自然语言处理能力,使得应用程序能够理解和生成人类语言。
首先,创建一个新的Blazor Server项目:
dotnet new blazorserver -o BlazorDeepSeekChat
// 添加HttpClient服务
builder.Services.AddScoped(sp => new HttpClient());
//设置HttpClient授权
// 添加配置
builder.Services.Configure<DeepSeekSettings>(
builder.Configuration.GetSection("DeepSeek"));
// 注册授权HttpClient
builder.Services.AddHttpClient("DeepSeek", (sp, client) => {
var settings = sp.GetRequiredService<IOptions<DeepSeekSettings>>().Value;
client.BaseAddress = new Uri(settings.ApiUrl);
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", settings.ApiKey);
});
@page "/"
@inject HttpClient Http
<h3>DeepSeek Chat</h3>
<div class="chat-container">
<div class="message-list">
@foreach (var message in messages)
{
<div class="message @message.Class">
<div class="message-content">@message.Content</div>
</div>
}
</div>
<div class="input-area">
<textarea @bind="inputText" placeholder="输入消息..." />
<button @onclick="SendMessage" :disabled="isSending">
@if (isSending) {
<span>发送中...</span>
} else {
<span>发送</span>
}
</button>
</div>
</div>
<style>
.chat-container {
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
.message-list {
height: 500px;
overflow-y: auto;
border: 1px solid #ccc;
padding: 10px;
margin-bottom: 10px;
}
.message {
margin: 10px 0;
padding: 8px 12px;
border-radius: 15px;
max-width: 70%;
}
.user {
background: #007bff;
color: white;
margin-left: auto;
}
.assistant {
background: #e9ecef;
margin-right: auto;
}
.input-area {
display: flex;
gap: 10px;
}
textarea {
flex: 1;
height: 80px;
padding: 10px;
}
</style>
using System.ComponentModel.DataAnnotations;
using System.Net.Http;
using System.Runtime;
using System.Text;
using System.Text.Json;
using Microsoft.AspNetCore.Components;
using Microsoft.Extensions.Logging;
namespaceBlazorDeepSeekChat.Pages;
publicpartialclassIndex
{
privatereadonly List<ChatMessage> messages = new();
privatestring inputText = string.Empty;
privatebool isSending = false;
private HttpClient _httpClient;
private IConfiguration _configuration;
// 使用 @inject 注入 HttpClient 和 IConfiguration
[Inject]
private HttpClient HttpClient { get; set; }
[Inject]
private IConfiguration Configuration { get; set; }
protected override void OnInitialized()
{
_httpClient = HttpClient;
_configuration = Configuration;
// 设置 API 地址
_httpClient.BaseAddress = new Uri(_configuration["DeepSeek:ApiUrl"]);
// 添加认证头
_httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {_configuration["DeepSeek:ApiKey"]}");
}
private async Task SendMessage()
{
if (string.IsNullOrWhiteSpace(inputText) || isSending) return;
try
{
var payload = new
{
model = "deepseek-chat",
messages = new[] { new { role = "user", content = inputText } },
temperature = "0.7",
max_tokens = 1000
};
try
{
// 创建请求内容
var requestContent = new StringContent(inputText, Encoding.UTF8, "application/json");
// 发送 POST 请求
//var response = await _httpClient.PostAsync(_configuration["DeepSeek:ApiUrl"], requestContent);
var response = await _httpClient.PostAsJsonAsync(_configuration["DeepSeek:ApiUrl"], payload);
response.EnsureSuccessStatusCode();
var result = await response.Content.ReadFromJsonAsync<DeepSeekResponse>();
var assistantMessage = new ChatMessage("assistant", result?.Choices[0].Message.Content ?? "");
messages.Add(assistantMessage);
//return result?.Choices[0].Message.Content ?? string.Empty;
}
catch (HttpRequestException ex)
{
Console.WriteLine($"HTTP Error: {ex.StatusCode}");
Console.WriteLine($"Response: {ex.Message}");
thrownew Exception("API 请求失败,请检查配置和网络连接。");
}
}
catch (Exception ex)
{
messages.Add(new ChatMessage("error", $"错误: {ex.Message}"));
}
finally
{
isSending = false;
}
}
private record ChatMessage(string Role, string Content)
{
publicstring Class => Role switch
{
"user" => "user",
"assistant" => "assistant",
_ => "error"
};
}
privateclassDeepSeekResponse
{
public List<Choice> Choices { get; set; } = new();
publicclassChoice
{
public Message Message { get; set; } = new();
}
publicclassMessage
{
publicstring Content { get; set; } = string.Empty;
}
}
}
{
"DeepSeek": {
"ApiKey": "api_key",
"ApiUrl": "https://api.deepseek.com/v1/chat/completions"
}
}
DeepSeekSettings 实体
public class DeepSeekSettings
{
/// <summary>
/// DeepSeek API 的基础地址
/// </summary>
public string ApiUrl { get; set; } = string.Empty;
/// <summary>
/// DeepSeek API 的访问密钥
/// </summary>
public string ApiKey { get; set; } = string.Empty;
/// <summary>
/// 默认使用的模型名称
/// </summary>
public string DefaultModel { get; set; } = "deepseek-chat";
/// <summary>
/// API 请求的温度参数(控制生成文本的随机性)
/// </summary>
public double Temperature { get; set; } = 0.7;
/// <summary>
/// API 请求的最大令牌数(控制生成文本的长度)
/// </summary>
public int MaxTokens { get; set; } = 1000;
}