繁体   English   中英

您如何为 aspnetcore 实现自定义 ConnectionHandler?

[英]How do you implement a custom ConnectionHandler for aspnetcore?

我查看了 github 存储库中的示例,但是当我开发流程时,在访问映射到自定义 ConnectionHandler 的路由时,我得到“需要连接 ID”。 我的日志消息永远不会被打印出来,我也不会使用调试器进入实现。

启动:

        builder.Services.AddConnections();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapConnectionHandler<CustomDelegationHandler>("/proxy/{id}");
        });

执行:

public class CustomDelegationHandler : ConnectionHandler
{
    private readonly ILogger<CustomDelegationHandler> _logger;

    public CustomDelegationHandler(ILogger<CustomDelegationHandler> logger)
    {
        _logger = logger;
    }

    public override async Task OnConnectedAsync(ConnectionContext connection)
    {
        _logger.LogWarning("Connection incomming");

        while (true)
        {
            var result = await connection.Transport.Input.ReadAsync();
            var buffer = result.Buffer;
            try
            {
                if (!buffer.IsEmpty)
                {
                    var stream = new MemoryStream();
                    var data = buffer.ToArray();
                    await stream.WriteAsync(data, 0, data.Length);
                    stream.Position = 0;
                }
                else if (result.IsCompleted)
                {
                    break;
                }
            }
            finally
            {
                connection.Transport.Input.AdvanceTo(buffer.End);
            }
        }
    }
}

您需要添加如下连接,它将 map 自定义 ConnectionHandler:

public async Task<IActionResult> Index()
{
    var url = "https://localhost:yourPortNumber/proxy/1";
    var connection = new HttpConnection(new Uri(url));
    await connection.StartAsync();

    var bytes = Encoding.UTF8.GetBytes("aaaa");
    async Task SendMessage()
    {
        await connection.Transport.Output.WriteAsync(bytes);
    }
    // Send the receive concurrently so that back pressure is released
    // for server -> client sends
    await SendMessage();
    return View();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM