簡體   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