Dify接口api对接,流式接收流式返回(.net)

试了好多种方法除了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();
            }
        }
    }


}

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值