试了好多种方法除了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";
// 配置响应头以支持SSE
var 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();
}
}
}
}
最终测试结果-流式返回: