6.31长轮询事件处理程序

创建于 2026 年 8 月 17 日约 1 分钟读完

IHttpLongPollingEventHandler 接口允许您定义发送长轮询请求的预处理操作。通过实现该接口,您可以创建自定义的长轮询事件处理程序,例如 CustomLongPollingEventHandler 类:

cs
public class CustomLongPollingEventHandler : IHttpLongPollingEventHandler{    // 用于接收服务器返回 200~299 状态码的数据的操作    public Task OnDataReceivedAsync(HttpResponseMessage httpResponseMessage, CancellationToken cancellationToken) {}    // 用于接收服务器返回【非】 200~299 状态码的数据的操作    public Task OnErrorAsync(HttpResponseMessage httpResponseMessage, CancellationToken cancellationToken) {}    // 用于响应标头包含 X-End-Of-Stream 时触发的操作    public Task OnEndOfStreamAsync(HttpResponseMessage httpResponseMessage, CancellationToken cancellationToken) {}}

要在应用程序中启用此处理程序,请在 Startup.csProgram.cs 文件中注册 CustomLongPollingEventHandler 服务:

cs
services.TryAddSingleton<CustomLongPollingEventHandler>();

接下来,您可以在构建 HTTP 请求时指定此处理程序:

cs
HttpRequestBuilder.LongPolling("https://localhost:7044/HttpRemote/LongPolling"    , async (responseMessage, token) =>    {        Console.WriteLine(await responseMessage.Content.ReadAsStringAsync(cancellationToken));        await Task.CompletedTask;    })    .SetEventHandler<CustomLongPollingEventHandler>();HttpRequestBuilder.LongPolling("https://localhost:7044/HttpRemote/LongPolling"    , async (responseMessage, token) =>    {        Console.WriteLine(await responseMessage.Content.ReadAsStringAsync(cancellationToken));        await Task.CompletedTask;    })    .SetEventHandler(typeof(CustomLongPollingEventHandler));    // 使用类型的方式