-
Notifications
You must be signed in to change notification settings - Fork 10.4k
Blazor Disable Non-WebSockets Transports by Default #34644
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
c4b3a17
fab2c82
e03d084
f1dbafc
895afb2
ce0ba7d
b2dc979
dfd0128
3bb93eb
1c3e8f6
221503a
b55777f
61a27b7
6b6c71e
5f8b828
0668383
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Large diffs are not rendered by default.
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,6 +1,6 @@ | ||
import { DotNet } from '@microsoft/dotnet-js-interop'; | ||
import { Blazor } from './GlobalExports'; | ||
import { HubConnectionBuilder, HubConnection } from '@microsoft/signalr'; | ||
import { HubConnectionBuilder, HubConnection, HttpTransportType } from '@microsoft/signalr'; | ||
import { MessagePackHubProtocol } from '@microsoft/signalr-protocol-msgpack'; | ||
import { showErrorNotification } from './BootErrors'; | ||
import { shouldAutoStart } from './BootCommon'; | ||
|
@@ -85,7 +85,7 @@ async function initializeConnection(options: CircuitStartOptions, logger: Logger | |
(hubProtocol as unknown as { name: string }).name = 'blazorpack'; | ||
|
||
const connectionBuilder = new HubConnectionBuilder() | ||
.withUrl('_blazor') | ||
.withUrl('_blazor', HttpTransportType.WebSockets) | ||
.withHubProtocol(hubProtocol); | ||
|
||
options.configureSignalR(connectionBuilder); | ||
|
@@ -130,6 +130,17 @@ async function initializeConnection(options: CircuitStartOptions, logger: Logger | |
await connection.start(); | ||
} catch (ex) { | ||
unhandledError(connection, ex, logger); | ||
|
||
if (ex.innerErrors && ex.innerErrors.some(e => e.errorType === 'UnsupportedTransportError' && e.transport === 'WebSockets')) { | ||
showErrorNotification('Unable to connect, please ensure you are using an updated browser that supports WebSockets.'); | ||
} else if (ex.innerErrors && ex.innerErrors.some(e => e.errorType === 'FailedToStartTransportError' && e.transport === 'WebSockets')) { | ||
showErrorNotification('Unable to connect, please ensure WebSockets are available. A VPN or proxy may be blocking the connection.'); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Unable to connect, please ensure WebSockets are available on the server. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I'm not so sure about this as this message is end-user facing and hence I would like to avoid "on the server" as it has no end user configurability. Additionally, it may not be a server issue if the local client VPN/proxy is blocking the connection. |
||
} else if (ex.innerErrors && ex.innerErrors.some(e => e.errorType === 'DisabledTransportError' && e.transport === 'LongPolling')) { | ||
logger.log(LogLevel.Error, 'Unable to initiate a SignalR connection to the server. This might be because the server is not configured to support WebSockets. To troubleshoot this, visit https://aka.ms/blazor-server-websockets-error.'); | ||
TanayParikh marked this conversation as resolved.
Show resolved
Hide resolved
|
||
showErrorNotification(); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Why doesn't this one get a nice UI message? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This represents the case when the client is attempting WS and the server only supports long polling. There's no remedial action the end-user can take here so we just present the generic "Unhandled exception has occurred". Note the developer will be presented a message to check the console and they'll see this error message to resolve the issue. |
||
} else { | ||
showErrorNotification(); | ||
} | ||
} | ||
|
||
DotNet.attachDispatcher({ | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,124 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
using System.Linq; | ||
using System.Threading; | ||
using BasicTestApp; | ||
using BasicTestApp.Reconnection; | ||
using Microsoft.AspNetCore.Components.E2ETest.Infrastructure; | ||
using Microsoft.AspNetCore.Components.E2ETest.Infrastructure.ServerFixtures; | ||
using Microsoft.AspNetCore.E2ETesting; | ||
using OpenQA.Selenium; | ||
using TestServer; | ||
using Xunit; | ||
using Xunit.Abstractions; | ||
|
||
namespace Microsoft.AspNetCore.Components.E2ETest.ServerExecutionTests | ||
{ | ||
public class ServerTransportsTest : ServerTestBase<BasicTestAppServerSiteFixture<TransportsServerStartup>> | ||
{ | ||
public ServerTransportsTest( | ||
BrowserFixture browserFixture, | ||
BasicTestAppServerSiteFixture<TransportsServerStartup> serverFixture, | ||
ITestOutputHelper output) | ||
: base(browserFixture, serverFixture, output) | ||
{ | ||
} | ||
|
||
[Fact] | ||
public void DefaultTransportsWorksWithWebSockets() | ||
{ | ||
Navigate("/defaultTransport/Transports"); | ||
|
||
Browser.Exists(By.Id("startBlazorServerBtn")).Click(); | ||
|
||
var javascript = (IJavaScriptExecutor)Browser; | ||
Browser.True(() => (bool)javascript.ExecuteScript("return window['__aspnetcore__testing__blazor__start__script__executed__'] === true;")); | ||
|
||
AssertLogContainsMessages( | ||
"Starting up Blazor server-side application.", | ||
"WebSocket connected to ws://", | ||
"Received render batch with", | ||
"The HttpConnection connected successfully.", | ||
"Blazor server-side application started."); | ||
} | ||
|
||
[Fact] | ||
public void ErrorIfClientAttemptsLongPollingWithServerOnWebSockets() | ||
{ | ||
Navigate("/defaultTransport/Transports"); | ||
|
||
Browser.Exists(By.Id("startWithLongPollingBtn")).Click(); | ||
|
||
var javascript = (IJavaScriptExecutor)Browser; | ||
Browser.True(() => (bool)javascript.ExecuteScript("return window['__aspnetcore__testing__blazor__start__script__executed__'] === true;")); | ||
|
||
AssertLogContainsMessages( | ||
"Information: Starting up Blazor server-side application.", | ||
"Failed to start the connection: Error: Unable to connect to the server with any of the available transports.", | ||
"Failed to start the circuit."); | ||
|
||
var errorUiElem = Browser.Exists(By.Id("blazor-error-ui"), TimeSpan.FromSeconds(10)); | ||
Assert.NotNull(errorUiElem); | ||
Assert.Contains("An unhandled exception has occurred. See browser dev tools for details.", errorUiElem.GetAttribute("innerHTML")); | ||
Browser.Equal("block", () => errorUiElem.GetCssValue("display")); | ||
} | ||
|
||
[Fact] | ||
public void ErrorIfWebSocketsConnectionIsRejected() | ||
{ | ||
Navigate("/defaultTransport/Transports"); | ||
|
||
Browser.Exists(By.Id("startAndRejectWebSocketConnectionBtn")).Click(); | ||
|
||
var javascript = (IJavaScriptExecutor)Browser; | ||
Browser.True(() => (bool)javascript.ExecuteScript("return window['__aspnetcore__testing__blazor__start__script__executed__'] === true;")); | ||
|
||
AssertLogContainsMessages( | ||
"Information: Starting up Blazor server-side application.", | ||
"Selecting transport 'WebSockets'.", | ||
"Error: Failed to start the transport 'WebSockets': Error: Don't allow Websockets.", | ||
"Error: Failed to start the connection: Error: Unable to connect to the server with any of the available transports. Error: WebSockets failed: Error: Don't allow Websockets.", | ||
"Failed to start the circuit."); | ||
|
||
// Ensure error ui is visible | ||
var errorUiElem = Browser.Exists(By.Id("blazor-error-ui"), TimeSpan.FromSeconds(10)); | ||
Assert.NotNull(errorUiElem); | ||
Assert.Contains("Unable to connect, please ensure WebSockets are available. A VPN or proxy may be blocking the connection.", errorUiElem.GetAttribute("innerHTML")); | ||
Browser.Equal("block", () => errorUiElem.GetCssValue("display")); | ||
} | ||
|
||
[Fact] | ||
public void ErrorIfClientAttemptsWebSocketsWithServerOnLongPolling() | ||
{ | ||
Navigate("/longPolling/Transports"); | ||
|
||
Browser.Exists(By.Id("startBlazorServerBtn")).Click(); | ||
|
||
var javascript = (IJavaScriptExecutor)Browser; | ||
Browser.True(() => (bool)javascript.ExecuteScript("return window['__aspnetcore__testing__blazor__start__script__executed__'] === true;")); | ||
|
||
AssertLogContainsMessages( | ||
"Starting up Blazor server-side application.", | ||
"Unable to connect to the server with any of the available transports. LongPolling failed: Error: 'LongPolling' is disabled by the client.", | ||
"Unable to initiate a SignalR connection to the server. This might be because the server is not configured to support WebSockets. To troubleshoot this, visit"); | ||
|
||
var errorUiElem = Browser.Exists(By.Id("blazor-error-ui"), TimeSpan.FromSeconds(10)); | ||
Assert.NotNull(errorUiElem); | ||
Assert.Contains("An unhandled exception has occurred. See browser dev tools for details.", errorUiElem.GetAttribute("innerHTML")); | ||
Browser.Equal("block", () => errorUiElem.GetCssValue("display")); | ||
} | ||
|
||
void AssertLogContainsMessages(params string[] messages) | ||
{ | ||
var log = Browser.Manage().Logs.GetLog(LogType.Browser); | ||
foreach (var message in messages) | ||
{ | ||
Assert.Contains(log, entry => | ||
{ | ||
return entry.Message.Contains(message, StringComparison.InvariantCulture); | ||
}); | ||
} | ||
} | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
@page | ||
@addTagHelper "*, Microsoft.AspNetCore.Mvc.TagHelpers" | ||
|
||
<root><component type="typeof(BasicTestApp.Index)" render-mode="Server" /></root> | ||
|
||
<div id="blazor-error-ui"> | ||
An unhandled exception has occurred. See browser dev tools for details. | ||
<a href="" class="reload">Reload</a> | ||
<a class="dismiss">🗙</a> | ||
</div> | ||
|
||
<button id="startBlazorServerBtn" onclick="startBlazorServer()">Start Normally</button> | ||
<button id="startWithLongPollingBtn" onclick="startWithLongPolling()">Start with Long Polling</button> | ||
<button id="startAndRejectWebSocketConnectionBtn" onclick="startAndRejectWebSocketConnection()">Start with WebSockets and Reject Connection</button> | ||
|
||
<script src="_framework/blazor.server.js" autostart="false"></script> | ||
<script> | ||
console.log('Blazor server-side'); | ||
|
||
function startBlazorServer() { | ||
Blazor.start({ | ||
logLevel: 1, // LogLevel.Debug | ||
configureSignalR: builder => { | ||
builder.configureLogging("debug") // LogLevel.Debug | ||
} | ||
}).then(function () { | ||
window['__aspnetcore__testing__blazor__start__script__executed__'] = true; | ||
}); | ||
} | ||
|
||
function startWithLongPolling() { | ||
Blazor.start({ | ||
logLevel: 1, // LogLevel.Debug | ||
configureSignalR: builder => { | ||
builder.configureLogging("debug") // LogLevel.Debug | ||
.withUrl('_blazor', 4) // Long Polling (4) | ||
} | ||
}).then(function () { | ||
window['__aspnetcore__testing__blazor__start__script__executed__'] = true; | ||
}); | ||
} | ||
|
||
function WebSocketNotAllowed() { throw new Error("Don't allow Websockets."); } | ||
|
||
function startAndRejectWebSocketConnection() { | ||
Blazor.start({ | ||
logLevel: 1, // LogLevel.Debug | ||
configureSignalR: builder => { | ||
builder.configureLogging("debug") // LogLevel.Debug | ||
.withUrl('_blazor', { | ||
WebSocket: WebSocketNotAllowed, | ||
transport: 1, // WebSockets (1) | ||
}) | ||
} | ||
}).then(function () { | ||
window['__aspnetcore__testing__blazor__start__script__executed__'] = true; | ||
}); | ||
} | ||
</script> |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
using System; | ||
using System.Globalization; | ||
using Microsoft.AspNetCore.Builder; | ||
using Microsoft.AspNetCore.DataProtection; | ||
using Microsoft.AspNetCore.Hosting; | ||
using Microsoft.Extensions.Configuration; | ||
using Microsoft.Extensions.DependencyInjection; | ||
using Microsoft.Extensions.Hosting; | ||
|
||
namespace TestServer | ||
{ | ||
public class TransportsServerStartup : ServerStartup | ||
{ | ||
public TransportsServerStartup(IConfiguration configuration) | ||
: base (configuration) | ||
{ | ||
} | ||
|
||
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. | ||
public override void Configure(IApplicationBuilder app, IWebHostEnvironment env, ResourceRequestLog resourceRequestLog) | ||
{ | ||
if (env.IsDevelopment()) | ||
{ | ||
app.UseDeveloperExceptionPage(); | ||
} | ||
|
||
app.Map("/defaultTransport", app => | ||
{ | ||
app.UseStaticFiles(); | ||
|
||
app.UseRouting(); | ||
app.UseEndpoints(endpoints => | ||
{ | ||
endpoints.MapBlazorHub(); | ||
endpoints.MapFallbackToPage("/_ServerHost"); | ||
}); | ||
}); | ||
|
||
app.Map("/longPolling", app => | ||
{ | ||
app.UseStaticFiles(); | ||
|
||
app.UseRouting(); | ||
app.UseEndpoints(endpoints => | ||
{ | ||
endpoints.MapBlazorHub(configureOptions: options => | ||
{ | ||
options.Transports = Microsoft.AspNetCore.Http.Connections.HttpTransportType.LongPolling; | ||
Comment on lines
+50
to
+51
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 👍🏽 |
||
}); | ||
endpoints.MapFallbackToPage("/_ServerHost"); | ||
}); | ||
}); | ||
} | ||
} | ||
} |
Uh oh!
There was an error while loading. Please reload this page.