AITestController.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  1. using Microsoft.AspNetCore.Mvc;
  2. using OASystem.API.OAMethodLib.DeepSeekAPI;
  3. using OASystem.API.OAMethodLib.DoubaoAPI;
  4. using OASystem.API.OAMethodLib.HotmailEmail;
  5. using OASystem.API.OAMethodLib.HunYuanAPI;
  6. using OASystem.API.OAMethodLib.MicrosoftGraphMailbox;
  7. using OASystem.API.OAMethodLib.QiYeWeChatAPI;
  8. using OASystem.Domain.ViewModels.QiYeWeChat;
  9. using System.IO;
  10. using System.Threading.Tasks;
  11. using TencentCloud.Hunyuan.V20230901.Models;
  12. using OASystem.RedisRepository;
  13. namespace OASystem.API.Controllers
  14. {
  15. /// <summary>
  16. /// AI测试控制器
  17. /// </summary>
  18. [Route("api/[controller]")]
  19. public class AITestController : ControllerBase
  20. {
  21. private readonly IHunyuanService _hunyuanService;
  22. private readonly IDoubaoService _doubaoService;
  23. private readonly ILogger<AITestController> _logger;
  24. private readonly IQiYeWeChatApiService _qiYeWeChatApiService;
  25. private readonly IHotmailEmailService _hotmailEmailService;
  26. private readonly IMicrosoftGraphMailboxService _microsoftGraphMailboxService;
  27. private readonly IDeepSeekService _deepSeekService;
  28. public AITestController(
  29. IHunyuanService hunyuanService,
  30. IDoubaoService doubaoService,
  31. ILogger<AITestController> logger,
  32. IQiYeWeChatApiService qiYeWeChatApiService,
  33. IHotmailEmailService hotmailEmailService,
  34. IMicrosoftGraphMailboxService microsoftGraphMailboxService,
  35. IDeepSeekService deepSeekService)
  36. {
  37. _hunyuanService = hunyuanService;
  38. _doubaoService = doubaoService;
  39. _logger = logger;
  40. _qiYeWeChatApiService = qiYeWeChatApiService;
  41. _hotmailEmailService = hotmailEmailService;
  42. _microsoftGraphMailboxService = microsoftGraphMailboxService;
  43. _deepSeekService = deepSeekService;
  44. }
  45. #region 企业微信发送邮件测试
  46. /// <summary>
  47. /// 企业微信发送邮件测试
  48. /// </summary>
  49. [HttpPost("sendEmail")]
  50. public async Task<ActionResult<string>> SendEmail([FromForm] IFormFile[] feils)
  51. {
  52. try
  53. {
  54. var req = new EmailRequestDto()
  55. {
  56. ToEmails = new List<string> { "johnny.yang@pan-american-intl.com" },
  57. CcEmails = new List<string> { "Roy.lei@pan-american-intl.com" },
  58. BccEmails = new List<string> { "Roy.lei@pan-american-intl.com" },
  59. Subject = "测试邮件 - 来自企业微信API",
  60. Body = "这是一封通过企业微信API发送的测试邮件,包含附件。",
  61. Files = feils
  62. };
  63. var response = await _qiYeWeChatApiService.EmailSendAsync(req);
  64. return Ok(response);
  65. }
  66. catch (Exception ex)
  67. {
  68. _logger.LogError(ex, "调用企业微信邮件API失败。");
  69. return StatusCode(500, new { Message = "调用企业微信邮件API失败,请检查配置或网络。", Detail = ex.Message });
  70. }
  71. }
  72. #endregion
  73. #region 豆包 AI
  74. /// <summary>
  75. /// 豆包基础对话
  76. /// </summary>
  77. [HttpPost("doubao-chat")]
  78. public async Task<ActionResult<string>> DoubaoChat(string question, bool isThinking = false)
  79. {
  80. try
  81. {
  82. var messages = new List<DouBaoChatMessage>
  83. {
  84. new DouBaoChatMessage { Role = DouBaoRole.user, Content = question }
  85. };
  86. var options = new CompleteChatOptions
  87. {
  88. ThinkingOptions = new thinkingOptions { IsThinking = isThinking }
  89. };
  90. var response = await _doubaoService.CompleteChatAsync(messages, options);
  91. return Ok(response);
  92. }
  93. catch (Exception ex)
  94. {
  95. _logger.LogError(ex, "调用豆包API失败。");
  96. return StatusCode(500, new { Message = "调用豆包API失败", Detail = ex.Message });
  97. }
  98. }
  99. /// <summary>
  100. /// 豆包上传文件
  101. /// </summary>
  102. [HttpPost("doubao-upload")]
  103. public async Task<ActionResult<DoubaoFileResponse>> DoubaoUpload(IFormFile file, string purpose = "user_data")
  104. {
  105. if (file == null || file.Length == 0)
  106. return BadRequest("请选择要上传的文件");
  107. try
  108. {
  109. var stream = file.OpenReadStream();
  110. var existsFileExpand = new List<string> { "pdf", "docx" };
  111. if (!existsFileExpand.Contains(file.FileName.Split('.').Last().ToLower()))
  112. {
  113. return BadRequest("请上传pdf、docx文件!不支持其他文件");
  114. }
  115. if (file.FileName.Split('.').Last().ToLower() == "docx")
  116. {
  117. using var docxStream = file.OpenReadStream();
  118. var pdfStream = DoubaoService.ConvertDocxStreamToPdfStream(docxStream);
  119. stream = pdfStream;
  120. }
  121. var response = await _doubaoService.UploadFileAsync(stream, file.FileName, purpose);
  122. stream.Dispose();
  123. return Ok(response);
  124. }
  125. catch (Exception ex)
  126. {
  127. _logger.LogError(ex, "豆包上传文件失败");
  128. return StatusCode(500, new { Message = "上传失败", Detail = ex.Message });
  129. }
  130. }
  131. /// <summary>
  132. /// 豆包获取文件列表
  133. /// </summary>
  134. [HttpGet("doubao-files")]
  135. public async Task<ActionResult<DoubaoFileListResponse>> DoubaoListFiles()
  136. {
  137. try
  138. {
  139. var response = await _doubaoService.ListFilesAsync();
  140. return Ok(response);
  141. }
  142. catch (Exception ex)
  143. {
  144. _logger.LogError(ex, "获取豆包文件列表失败");
  145. return StatusCode(500, new { Message = "获取失败", Detail = ex.Message });
  146. }
  147. }
  148. /// <summary>
  149. /// 豆包删除文件
  150. /// </summary>
  151. [HttpDelete("doubao-file/{fileId}")]
  152. public async Task<ActionResult<bool>> DoubaoDeleteFile(string fileId)
  153. {
  154. try
  155. {
  156. var response = await _doubaoService.DeleteFileAsync(fileId);
  157. return Ok(response);
  158. }
  159. catch (Exception ex)
  160. {
  161. _logger.LogError(ex, "删除豆包文件失败");
  162. return StatusCode(500, new { Message = "删除失败", Detail = ex.Message });
  163. }
  164. }
  165. /// <summary>
  166. /// 豆包多模态对话(支持文本+图片)
  167. /// </summary>
  168. /// <param name="request">表单请求参数</param>
  169. [HttpPost("doubao-multimodal-chat")]
  170. public async Task<ActionResult<string>> DoubaoMultimodalChat([FromForm] DoubaoMultimodalChatRequest request)
  171. {
  172. if (string.IsNullOrWhiteSpace(request.Question))
  173. return BadRequest("问题不能为空");
  174. try
  175. {
  176. var contentItems = new List<DoubaoMultimodalContentItem>
  177. {
  178. new DoubaoMultimodalContentItem { Type = "text", Text = request.Question.Trim() }
  179. };
  180. if (!string.IsNullOrWhiteSpace(request.FileId))
  181. {
  182. contentItems.Add(new DoubaoMultimodalContentItem
  183. {
  184. Type = "file",
  185. FileId = request.FileId.Trim(),
  186. });
  187. }
  188. if (request.Image != null && request.Image.Length > 0)
  189. {
  190. using var ms = new MemoryStream();
  191. await request.Image.CopyToAsync(ms);
  192. var base64 = Convert.ToBase64String(ms.ToArray());
  193. var mimeType = request.Image.ContentType ?? "image/jpeg";
  194. var dataUrl = $"data:{mimeType};base64,{base64}";
  195. contentItems.Add(new DoubaoMultimodalContentItem
  196. {
  197. Type = "image_url",
  198. ImageUrl = new DoubaoMultimodalImageUrl { Url = dataUrl }
  199. });
  200. }
  201. var messages = new List<DoubaoMultimodalChatMessage>
  202. {
  203. new DoubaoMultimodalChatMessage
  204. {
  205. Role = "user",
  206. Content = contentItems
  207. }
  208. };
  209. var options = new CompleteMultimodalChatOptions
  210. {
  211. ThinkingOptions = new DoubaoMultimodalThinkingOptions
  212. {
  213. IsThinking = request.IsThinking,
  214. ReasoningEffort = "medium"
  215. }
  216. };
  217. var response = await _doubaoService.CompleteMultimodalChatAsync(messages, options);
  218. return Ok(response ?? string.Empty);
  219. }
  220. catch (Exception ex)
  221. {
  222. _logger.LogError(ex, "调用豆包多模态API失败。");
  223. return StatusCode(500, new { Message = "调用豆包多模态API失败", Detail = ex.Message });
  224. }
  225. }
  226. #endregion
  227. #region 混元 AI
  228. /// <summary>
  229. /// 基础对话示例
  230. /// </summary>
  231. [HttpPost("chat")]
  232. public async Task<ActionResult<string>> BasicChat(string question)
  233. {
  234. try
  235. {
  236. var response = await _hunyuanService.ChatCompletionsHunyuan_t1_latestAsync(question);
  237. return Ok(response);
  238. }
  239. catch (Exception ex)
  240. {
  241. _logger.LogError(ex, "调用腾讯云混元API失败。");
  242. return StatusCode(500, new { Message = "调用腾讯云API失败,请检查配置或网络。", Detail = ex.Message });
  243. }
  244. }
  245. /// <summary>
  246. /// 模拟“根据文件提问”的API端点
  247. /// 注意:此示例中,文件内容通过请求体传入。
  248. /// 实际场景中,文件内容可能来自用户上传并解析(如PDF、TXT解析为文本)后的结果。
  249. /// </summary>
  250. [HttpPost("ask-with-file")]
  251. public async Task<ActionResult<string>> AskBasedOnFile([FromBody] AskWithFileRequest request)
  252. {
  253. if (string.IsNullOrEmpty(request.FileContent) || string.IsNullOrEmpty(request.Question))
  254. {
  255. return BadRequest(new { Message = "FileContent和Question字段不能为空。" });
  256. }
  257. try
  258. {
  259. var answer = await _hunyuanService.AskWithFileContextAsync(request.FileContent, request.Question, request.Model);
  260. return Ok(answer);
  261. }
  262. catch (Exception ex)
  263. {
  264. _logger.LogError(ex, "处理基于文件的提问失败。");
  265. return StatusCode(500, new { Message = "处理请求失败。", Detail = ex.Message });
  266. }
  267. }
  268. /// <summary>
  269. /// 用于测试的GET端点,快速验证服务可用性(使用示例数据)
  270. /// </summary>
  271. [HttpGet("test-file-query")]
  272. public async Task<ActionResult<string>> TestFileQuery()
  273. {
  274. // 示例文件内容和问题
  275. var sampleFileContent = "在软件开发中,依赖注入(Dependency Injection)是一种设计模式,用于实现控制反转(Inversion of Control, IoC)。它允许在类外部创建依赖对象,并通过构造函数、属性或方法将其‘注入’到类中,从而降低类之间的耦合度。";
  276. var sampleQuestion = "依赖注入的主要目的是什么?";
  277. var model = "hunyuan-lite"; // 可使用 "hunyuan-pro" 等
  278. try
  279. {
  280. var answer = await _hunyuanService.AskWithFileContextAsync(sampleFileContent, sampleQuestion, model);
  281. return Ok($"测试成功。问题:'{sampleQuestion}'\n回答:{answer}");
  282. }
  283. catch (Exception ex)
  284. {
  285. _logger.LogError(ex, "测试文件提问失败。");
  286. return StatusCode(500, new { Message = "测试失败。", Detail = ex.Message });
  287. }
  288. }
  289. /// <summary>
  290. /// 用于“根据文件提问”的请求体
  291. /// </summary>
  292. public class AskWithFileRequest
  293. {
  294. public string FileContent { get; set; } = string.Empty;
  295. public string Question { get; set; } = string.Empty;
  296. public string Model { get; set; } = "hunyuan-lite";
  297. }
  298. /// <summary>
  299. /// 豆包多模态对话请求体(form-data)
  300. /// </summary>
  301. public class DoubaoMultimodalChatRequest
  302. {
  303. public string Question { get; set; } = string.Empty;
  304. public IFormFile? Image { get; set; }
  305. public bool IsThinking { get; set; } = false;
  306. public string FileId { get; set; } = string.Empty;
  307. }
  308. #endregion
  309. #region DeepSeek 测试
  310. /// <summary>
  311. /// DeepSeek 带上下文的流式对话测试。响应为 NDJSON:每行一条 JSON,phase 为 reasoning、content 或 error。
  312. /// </summary>
  313. [HttpPost("deepseek-chat-stream-with-history")]
  314. public async Task<IActionResult> DeepSeekChatStreamWithHistory(
  315. [FromBody] DeepSeekChatStreamHistoryTestRequest request,
  316. CancellationToken cancellationToken = default)
  317. {
  318. if (request?.Messages == null || request.Messages.Count == 0)
  319. return BadRequest(new { message = "Messages 不能为空,且至少包含一条 user/system/assistant 消息。" });
  320. Response.ContentType = "application/x-ndjson; charset=utf-8";
  321. Response.Headers["Cache-Control"] = "no-cache";
  322. static string NdjsonLine(DeepSeekStreamChunk c) => JsonConvert.SerializeObject(new
  323. {
  324. phase = c.Phase == DeepSeekStreamPhase.Reasoning ? "reasoning" : "content",
  325. text = c.Text
  326. });
  327. try
  328. {
  329. await foreach (var chunk in _deepSeekService.ChatStreamWithHistoryAsync(
  330. request.Messages,
  331. string.IsNullOrWhiteSpace(request.Model) ? "deepseek-chat" : request.Model!.Trim(),
  332. request.Temperature,
  333. request.MaxTokens))
  334. {
  335. cancellationToken.ThrowIfCancellationRequested();
  336. await Response.WriteAsync(NdjsonLine(chunk) + "\n", cancellationToken);
  337. await Response.Body.FlushAsync(cancellationToken);
  338. }
  339. }
  340. catch (OperationCanceledException)
  341. {
  342. }
  343. catch (Exception ex)
  344. {
  345. _logger.LogError(ex, "DeepSeek 带历史流式对话失败");
  346. await Response.WriteAsync(
  347. JsonConvert.SerializeObject(new { phase = "error", text = ex.Message }) + "\n",
  348. cancellationToken);
  349. }
  350. return new EmptyResult();
  351. }
  352. /// <summary>
  353. /// DeepSeek 流式对话(含多轮)请求体
  354. /// </summary>
  355. public class DeepSeekChatStreamHistoryTestRequest
  356. {
  357. public List<DeepSeekHistoryMessage> Messages { get; set; } = new();
  358. public string? Model { get; set; } = "deepseek-chat";
  359. public float Temperature { get; set; } = 0.7f;
  360. public int MaxTokens { get; set; } = 4000;
  361. }
  362. #endregion
  363. #region hotmail 测试
  364. [HttpPost("send-notification")]
  365. public async Task<IActionResult> SendNotification([FromBody] EmailRequest request)
  366. {
  367. if (string.IsNullOrEmpty(request.Email))
  368. return BadRequest("邮箱地址不能为空");
  369. // 调用服务
  370. bool isSent = await _hotmailEmailService.SendEmailAsync(
  371. request.Email,
  372. "OASystem 业务提醒",
  373. $"<p>您有一条新的待办事项:<b>{request.Content}</b></p>"
  374. );
  375. if (isSent)
  376. return Ok(new { code = 200, msg = "发送成功" });
  377. return StatusCode(500, "邮件发送失败,请检查服务器配置或应用密码");
  378. }
  379. // 定义请求实体
  380. public class EmailRequest
  381. {
  382. public string Email { get; set; } = string.Empty;
  383. public string Content { get; set; } = string.Empty;
  384. }
  385. #endregion
  386. #region Microsoft Graph 邮箱测试(仅访问令牌)
  387. private const string GraphAccessTokenHeader = "X-Graph-Access-Token";
  388. /// <summary>
  389. /// 优先级:请求头 X-Graph-Access-Token → 查询 graphAccessToken → bodyToken(发信)。
  390. /// </summary>
  391. private string? ResolveGraphAccessToken(string? queryToken = null, string? bodyToken = null)
  392. {
  393. var header = Request.Headers[GraphAccessTokenHeader].FirstOrDefault();
  394. if (!string.IsNullOrWhiteSpace(header))
  395. return header.Trim();
  396. if (!string.IsNullOrWhiteSpace(queryToken))
  397. return queryToken.Trim();
  398. if (!string.IsNullOrWhiteSpace(bodyToken))
  399. return bodyToken.Trim();
  400. return null;
  401. }
  402. /// <summary>
  403. /// 查询当前用户 GET /v1.0/me。必须提供 Graph 访问令牌。
  404. /// </summary>
  405. [HttpGet("graph-mail/me")]
  406. public async Task<IActionResult> GraphMailMe(
  407. [FromQuery] string? graphAccessToken = null,
  408. CancellationToken cancellationToken = default)
  409. {
  410. var bearer = ResolveGraphAccessToken(graphAccessToken);
  411. if (string.IsNullOrWhiteSpace(bearer))
  412. return Unauthorized(new { message = "必须提供 Microsoft Graph 访问令牌:请求头 X-Graph-Access-Token 或查询参数 graphAccessToken" });
  413. try
  414. {
  415. var json = await _microsoftGraphMailboxService.GetMeRawJsonAsync(bearer, cancellationToken);
  416. if (string.IsNullOrEmpty(json))
  417. return StatusCode(502, new { message = "Graph 返回空正文" });
  418. return Content(json, "application/json");
  419. }
  420. catch (Exception ex)
  421. {
  422. _logger.LogError(ex, "Graph Mail /me 失败");
  423. return StatusCode(500, new { message = ex.Message });
  424. }
  425. }
  426. /// <summary>
  427. /// 查询收件箱。必须提供 Graph 访问令牌(需 Mail.Read)。默认 sinceUtc 为 UTC 近 24 小时。
  428. /// </summary>
  429. /// <param name="sinceUtc">起始时间(UTC),ISO8601</param>
  430. /// <param name="graphAccessToken">或使用请求头 X-Graph-Access-Token</param>
  431. /// <param name="cancellationToken">取消标记</param>
  432. [HttpGet("graph-mail/inbox")]
  433. public async Task<IActionResult> GraphMailInbox(
  434. [FromQuery] DateTime? sinceUtc = null,
  435. [FromQuery] string? graphAccessToken = null,
  436. CancellationToken cancellationToken = default)
  437. {
  438. var bearer = ResolveGraphAccessToken(graphAccessToken);
  439. if (string.IsNullOrWhiteSpace(bearer))
  440. return Unauthorized(new { message = "必须提供 Microsoft Graph 访问令牌:请求头 X-Graph-Access-Token 或查询参数 graphAccessToken" });
  441. var since = sinceUtc ?? DateTime.UtcNow.AddHours(-24);
  442. try
  443. {
  444. var json = await _microsoftGraphMailboxService.GetInboxMessagesJsonSinceAsync(since, bearer, cancellationToken);
  445. if (string.IsNullOrEmpty(json))
  446. return StatusCode(502, new { message = "Graph 返回空正文" });
  447. return Content(json, "application/json");
  448. }
  449. catch (Exception ex)
  450. {
  451. _logger.LogError(ex, "Graph Mail inbox 失败");
  452. return StatusCode(500, new { message = ex.Message });
  453. }
  454. }
  455. /// <summary>
  456. /// Graph sendMail 纯文本。必须提供令牌(需 Mail.Send):头 / 查询 / Body.graphAccessToken。
  457. /// </summary>
  458. [HttpPost("graph-mail/send")]
  459. public async Task<IActionResult> GraphMailSend(
  460. [FromBody] GraphMailSendTestRequest request,
  461. [FromQuery] string? graphAccessToken = null,
  462. CancellationToken cancellationToken = default)
  463. {
  464. if (request == null || string.IsNullOrWhiteSpace(request.ToEmail))
  465. return BadRequest(new { message = "ToEmail 不能为空" });
  466. var bearer = ResolveGraphAccessToken(graphAccessToken, request.GraphAccessToken);
  467. if (string.IsNullOrWhiteSpace(bearer))
  468. return Unauthorized(new { message = "必须提供 Microsoft Graph 访问令牌:X-Graph-Access-Token、?graphAccessToken 或 Body.graphAccessToken" });
  469. var subject = string.IsNullOrWhiteSpace(request.Subject)
  470. ? $"OASystem Graph 测试邮件 {DateTime.Now:yyyy-MM-dd HH:mm:ss}"
  471. : request.Subject!;
  472. var body = request.Body ?? string.Empty;
  473. try
  474. {
  475. await _microsoftGraphMailboxService.SendMailAsync(request.ToEmail.Trim(), subject, body, bearer, cancellationToken);
  476. return Ok(new { ok = true, message = "sendMail 已提交", to = request.ToEmail.Trim(), subject });
  477. }
  478. catch (HttpRequestException ex)
  479. {
  480. return StatusCode(502, new { message = "Graph HTTP 错误", detail = ex.Message });
  481. }
  482. catch (Exception ex)
  483. {
  484. _logger.LogError(ex, "Graph Mail send 失败");
  485. return StatusCode(500, new { message = ex.Message });
  486. }
  487. }
  488. public class EmailAuthRedisCache
  489. {
  490. public string? AccessToken { get; set; }
  491. public string? HomeAccountId { get; set; }
  492. public string? UserTokenCacheBase64 { get; set; }
  493. public string? ClientId { get; set; }
  494. }
  495. /// <summary>
  496. /// 从 Redis 读取 MSAL 缓存与 HomeAccountId,静默刷新 Graph access_token。
  497. /// </summary>
  498. [HttpGet("graph-mail/refresh-token")]
  499. public async Task<IActionResult> RefreshAccessToken([FromQuery] string? redisKey = null)
  500. {
  501. var key = string.IsNullOrWhiteSpace(redisKey) ? "Email:AuthCache:345" : redisKey.Trim();
  502. var redis = RedisFactory.CreateRedisRepository();
  503. var json = await redis.StringGetRawAsync(key);
  504. if (string.IsNullOrWhiteSpace(json))
  505. {
  506. return BadRequest(new { message = $"Redis 键 {key} 不存在或为空" });
  507. }
  508. EmailAuthRedisCache? cacheEntry;
  509. try
  510. {
  511. cacheEntry = JsonConvert.DeserializeObject<EmailAuthRedisCache>(json);
  512. }
  513. catch (JsonException ex)
  514. {
  515. _logger.LogWarning(ex, "Redis 键 {Key} 内容不是合法 JSON(应用 StringGetRawAsync + JSON,勿用 StringGetAsync<T>,后者为 BinaryFormatter)", key);
  516. return BadRequest(new { message = "Redis 值为 JSON 文本时须用 StringGetRawAsync 再反序列化;StringGetAsync<T> 仅适用于 BinaryFormatter 写入的数据", detail = ex.Message });
  517. }
  518. if (cacheEntry == null
  519. || string.IsNullOrWhiteSpace(cacheEntry.UserTokenCacheBase64)
  520. || string.IsNullOrWhiteSpace(cacheEntry.HomeAccountId))
  521. {
  522. return BadRequest(new { message = "JSON 中缺少 UserTokenCacheBase64 或 HomeAccountId" });
  523. }
  524. var accessToken = await _microsoftGraphMailboxService.RefreshAccessTokenAsync(
  525. cacheEntry.ClientId,
  526. "common",
  527. new[] { "Mail.Read", "User.Read", "Mail.Send" },
  528. cacheEntry.UserTokenCacheBase64,
  529. cacheEntry.HomeAccountId);
  530. return Ok(new { accessToken });
  531. }
  532. /// <summary>
  533. /// Graph 发信测试请求体
  534. /// </summary>
  535. public class GraphMailSendTestRequest
  536. {
  537. public string ToEmail { get; set; } = string.Empty;
  538. public string? Subject { get; set; }
  539. public string? Body { get; set; }
  540. /// <summary>Microsoft Graph 访问令牌(也可用请求头 X-Graph-Access-Token)</summary>
  541. public string? GraphAccessToken { get; set; }
  542. }
  543. #endregion
  544. }
  545. }