var config = Configuration.Builder(new Uri(apiUrl))
    .Method(HttpMethod.Post)
    .RequestBody(input.ToJson(), "application/json")
    .RequestHeader("Accept", "text/event-stream")
    .Build();

var sseClient = new EventSource(config);

sseClient.Error += (sender, e) =>
{
    _httpContextAccessor.Bah(FrontErrorCode.AIRequestError, e.Exception.Message);
};

sseClient.MessageReceived += (sender, e) =>
{
    _httpContextAccessor.WriteAsync($"data: {e.Message.Data}").Wait();
};

sseClient.Closed += (sender, e) =>
{
    _httpContextAccessor.WriteAsync("[DONE]", "").Wait();
    usageDto.IsSuccess = true;
    sseClient.Dispose();//不在Closed中进行Dispose会导致重复请求
};

await sseClient.StartAsync();
最后修改:2023 年 09 月 05 日
如果觉得我的文章对你有用,请随意赞赏