如何在 Blazor 服务器中设置 Websocket?

问题描述 投票:0回答:1

我正在尝试在我的 Blazor Server 应用程序中创建 WebSocket 服务器,这是我的 Program.cs:

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
builder.Services.AddSingleton<WeatherForecastService>();
builder.Services.AddScoped<DialogService>();
builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowAll", builder =>
    {
        builder.AllowAnyOrigin()
               .AllowAnyMethod()
               .AllowAnyHeader();
    });
});
var app = builder.Build();
app.Use(async (context, next) =>
{
    var logger = context.RequestServices.GetRequiredService<ILogger<Program>>();
    logger.LogInformation("Request path: " + context.Request.Path);
    if (context.Request.Path == "/ws")
    {
        if (context.WebSockets.IsWebSocketRequest)
        {
            var webSocket = await context.WebSockets.AcceptWebSocketAsync();
            var webSocketHandler = context.RequestServices.GetRequiredService<IWebSocketHandler>();
            await webSocketHandler.HandleWebSocketAsync(context, webSocket);
        }
        else
        {
            context.Response.StatusCode = 400;
        }
    }
    else
    {
        await next();
    }
});
var webSocketOptions = new WebSocketOptions()
{
    KeepAliveInterval = TimeSpan.FromSeconds(120),

};

app.UseWebSockets(webSocketOptions);


if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
    app.UseCors("AllowAll");
    app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.MapBlazorHub();
app.MapFallbackToPage("/_Host");
app.Run();

我正在尝试使用 WebSocketClient chrome 扩展来测试它。但是,连接请求被阻止,因为

context.WebSockets.IsWebSocketRequest
false

我启用了allow-insecure-localhost,还运行了 dotnet dev-certs https --trust... 我尝试更改 launchSettings.json 中的端口;结果都一样

websocket blazor blazor-server-side
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.