您的位置:首页 > 文旅 > 旅游 > 泉州网站设计师招聘_遵义官网建设_seo优化的优点_代刷网站推广链接0元价格

泉州网站设计师招聘_遵义官网建设_seo优化的优点_代刷网站推广链接0元价格

2025/4/10 21:54:53 来源:https://blog.csdn.net/q584565828/article/details/146947766  浏览:    关键词:泉州网站设计师招聘_遵义官网建设_seo优化的优点_代刷网站推广链接0元价格
泉州网站设计师招聘_遵义官网建设_seo优化的优点_代刷网站推广链接0元价格

试了好多种方法除了Console.WriteLine()能打印出来,试了好些方法都不行,不是报错就是打印只有一行,要么就是接收完才返回...下面代码实现调用api接收流式数据,并进行流式返回给前端:

using Furion.HttpRemote;
using System.Net.Http.Headers;
using System.Text;namespace Admin.NET.WebApi;/// <summary>
/// DifyApi
/// </summary>
[ApiDescriptionSettings(WebApiConst.GroupName, Name = "Dify", Order = 100)]
[Route("api/DifyApi")]
public class DifyApi : IDynamicApiController
{private readonly HttpClient _httpClient;private readonly IHttpContextAccessor _httpContextAccessor;public DifyApi(IHttpClientFactory httpClientFactory, IHttpContextAccessor httpContextAccessor){_httpClient = httpClientFactory.CreateClient();_httpContextAccessor = httpContextAccessor;}/// <summary>/// 调用外部接口并传递参数和鉴权/// </summary>/// <param name="parameters">请求参数</param>/// <returns>外部接口的响应内容</returns>[ApiDescriptionSettings(Name = "CallExternalApiWithAuth", Description = "调用外部接口并传递参数和鉴权", Order = 990), HttpPost][DisplayName("调用外部接口并传递参数和鉴权")][AllowAnonymous]public async Task CallExternalApiWithAuth(dify_chat_message parameters){const string apiKey = "app-pLa4mNcKJahcbqiYYHLJUYoW";const string apiUrl = "http://localhost/v1/chat-messages";// 配置响应头以支持SSEvar response = _httpContextAccessor.HttpContext.Response;response.Headers.Append("Content-Type", "text/event-stream");response.Headers.Append("Cache-Control", "no-cache");response.Headers.Append("Connection", "keep-alive");var client = _httpClient;client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));/*// 确保请求启用流式返回if (parameters.stream == null){parameters.stream = true;}*/using var request = new HttpRequestMessage(HttpMethod.Post, apiUrl);request.Content = new StringContent(JsonConvert.SerializeObject(parameters), Encoding.UTF8, "application/json");using var apiResponse = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);apiResponse.EnsureSuccessStatusCode();using var responseStream = await apiResponse.Content.ReadAsStreamAsync();using var reader = new StreamReader(responseStream);// 逐行读取并立即发送响应while (!reader.EndOfStream){var line = await reader.ReadLineAsync();if (line != null){await response.WriteAsync(line + "\n");await response.Body.FlushAsync();}}}}

最终测试结果-流式返回:

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com