Skip to content

Override ResolveComponentForRenderMode in WebViewRenderer to treat all render modes as no-ops - #65876

Merged
javiercn merged 1 commit into
mainfrom
copilot/fix-webviewrenderer-no-op-support
Jun 17, 2026
Merged

javiercn merged 1 commit into
mainfrom
copilot/fix-webviewrenderer-no-op-support

Conversation

Copilot AI commented Mar 19, 2026 •

Copy link
Copy Markdown
Contributor

WebViewRenderer did not override ResolveComponentForRenderMode, causing NotSupportedException when Blazor Hybrid (MAUI) apps render components annotated with @rendermode InteractiveAuto (or any per-page/component render mode). Since WebView is always interactive, all render modes are no-ops.

Description

  • WebViewRenderer: Override ResolveComponentForRenderMode to unconditionally return componentActivator.CreateInstance(componentType) for any render mode, matching the pattern used by RemoteRenderer (Server-only) and WebAssemblyRenderer (WASM-only) but without restricting to specific render mode types.
protected override IComponent ResolveComponentForRenderMode(
    [DynamicallyAccessedMembers(Component)] Type componentType,
    int? parentComponentId,
    IComponentActivator componentActivator,
    IComponentRenderMode renderMode)
{
    // Blazor Hybrid is always interactive, so all render modes are treated as no-ops.
    return componentActivator.CreateInstance(componentType);
}
  • Tests: Added unit tests to WebViewManagerTests covering InteractiveServer, InteractiveWebAssembly, InteractiveAuto, and custom/unknown render modes — all verify successful rendering without NotSupportedException.

  • You've read the Contributor Guide and Code of Conduct.

  • You've included unit or integration tests for your change, where applicable.

  • You've included inline docs for your change, where applicable.

  • There's an open issue for the PR that you are making. If you'd like to propose a new feature or change, please open an issue to discuss the change or find an existing issue.

Original prompt

This section details on the original issue you should resolve

<issue_title>Blazor Hybrid (WebViewRenderer) should support per-page/component render modes as no-ops</issue_title>
<issue_description>Tracking issue: dotnet/maui#31945

Background

The maui-blazor-web solution template enables sharing Razor components between Blazor Web and Blazor Hybrid (MAUI) apps via a shared Razor Class Library (RCL). When using per-page/component interactivity (e.g., @rendermode InteractiveAuto on a page), the Blazor Web app works fine, but the MAUI Blazor Hybrid app throws:

NotSupportedException: Cannot supply a component of type 'Counter' because the current platform does not support the render mode 'InteractiveAuto'.

This is because WebViewRenderer does not override ResolveComponentForRenderMode, and the Renderer base class throws by default.

Problem

  • WebViewRenderer (source) inherits from WebRenderer but does not override ResolveComponentForRenderMode.
  • Renderer.ResolveComponentForRenderMode (source) throws NotSupportedException by default.
  • PageContext (source) creates WebViewRenderer privately — consumers (like MAUI's BlazorWebView) have no way to provide a custom renderer or override this behavior.

Why this cannot be solved in MAUI

Both WebViewRenderer and PageContext are internal sealed in this repo. WebViewManager (which MAUI subclasses) creates PageContext in its internal AttachToPageAsync method, and PageContext creates WebViewRenderer in its constructor. There is no factory pattern, DI hook, or extensibility point that would allow MAUI to customize the renderer.

Proposed Solutions

As @SteveSandersonMS suggested in dotnet/maui#31945:

Option A (minimal — unconditional override): Override ResolveComponentForRenderMode in WebViewRenderer to treat all interactive render modes as no-ops, since Blazor Hybrid is always interactive. This follows the same pattern as RemoteRenderer and WebAssemblyRenderer:

// In WebViewRenderer.cs
protected internal override IComponent ResolveComponentForRenderMode(
    Type componentType,
    int? parentComponentId,
    IComponentActivator componentActivator,
    IComponentRenderMode renderMode)
{
    // Blazor Hybrid is always interactive — all render modes are no-ops
    return componentActivator.CreateInstance(componentType);
}

Option B (extensible): Add extensibility to PageContext or WebViewRenderer so that BlazorWebView consumers can configure render mode resolution behavior.

Option C (longer-term, from Steve's suggestion): Introduce a generic Interactive render mode that web apps resolve based on global configuration, while WebView treats as a no-op.

Option D (AppContext switch — allows host app to opt in): Add an AppContext switch that the Renderer base class checks before throwing in its default ResolveComponentForRenderMode. This follows the existing pattern used in the Components area (e.g., Microsoft.AspNetCore.Components.Unsupported.DisablePropertyInjection in ComponentFactory.cs and Microsoft.AspNetCore.Components.Routing.RegexConstraintSupport in RegexConstraintSupport.cs):

// In Renderer.cs — change the default fallback behavior
private static readonly bool _suppressRenderModeExceptions =
    AppContext.TryGetSwitch(
        "Microsoft.AspNetCore.Components.SuppressUnsupportedRenderModes",
        out var suppress) && suppress;

protected internal virtual IComponent ResolveComponentForRenderMode(
    Type componentType,
    int? parentComponentId,
    IComponentActivator componentActivator,
    IComponentRenderMode renderMode)
{
    if (_suppressRenderModeExceptions)
    {
        // When the switch is set, treat unsupported render modes as no-ops.
        // This enables Blazor Hybrid and other hosts where everything is already interactive.
        return componentActivator.CreateInstance(componentType);
    }

    throw new NotSupportedException(
        $"Cannot supply a component of type '{ componentType }' because the current platform "
        + $"does not support the render mode '{renderMode}'.");
}

The host app (e.g., MAUI) would set the switch at startup:

// In MauiProgram.cs (or set automatically by MAUI's BlazorWebView handler):
AppContext.SetSwitch(
    "Microsoft.AspNetCore.Components.SuppressUnsupportedRenderModes", true);

Or via MSBuild (no code needed):

<ItemGroup>
  <RuntimeHostConfigurationOption
    Include="Microsoft.AspNetCore.Components.SuppressUnsupportedRenderModes"
    Value="true" />
</Ite...

</details>



<!-- START COPILOT CODING AGENT SUFFIX -->

- Fixes dotnet/aspnetcore#65875

<!-- START COPILOT CODING AGENT TIPS -->
---

📍 Connect Copilot coding agent with [Jira](https://gh.io/cca-jira-docs), [Azure Boards](https://gh.io/cca-azure-boards-docs) or [Linear](https://gh.io/cca-linear-docs) to delegate work to Copilot in one click without leaving your project management tool.

Copilot AI changed the title [WIP] Fix WebViewRenderer to handle per-page/component render modes Override ResolveComponentForRenderMode in WebViewRenderer to treat all render modes as no-ops Mar 19, 2026
Copilot AI requested a review from javiercn March 19, 2026 18:32
@github-actions github-actions Bot added the area-blazor Includes: Blazor, Razor Components label Mar 19, 2026
@javiercn
javiercn marked this pull request as ready for review May 8, 2026 10:41
Copilot AI review requested due to automatic review settings May 8, 2026 10:41
@javiercn
javiercn requested a review from a team as a code owner May 8, 2026 10:41
@javiercn
javiercn force-pushed the copilot/fix-webviewrenderer-no-op-support branch from 08630b0 to a2d599a Compare May 8, 2026 10:41

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR updates Blazor Hybrid’s WebViewRenderer to treat per-component/per-page render modes as no-ops (since WebView rendering is always interactive), preventing NotSupportedException when components specify render modes like InteractiveAuto.

Changes:

  • Override WebViewRenderer.ResolveComponentForRenderMode to always instantiate the requested component type regardless of render mode.
  • Add WebViewManagerTests coverage to ensure rendering succeeds for InteractiveServer, InteractiveWebAssembly, InteractiveAuto, and an unknown/custom render mode.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.

File Description
src/Components/WebView/WebView/src/Services/WebViewRenderer.cs Overrides render-mode component resolution to always create the component instance (render modes become no-ops in Hybrid).
src/Components/WebView/WebView/test/WebViewManagerTests.cs Adds unit tests verifying Hybrid rendering does not throw for built-in and custom render modes.

Comment on lines +114 to +132
[Fact]
public async Task CanRenderComponentWithInteractiveServerRenderMode()
{
// Arrange
var services = RegisterTestServices().AddTestBlazorWebView().BuildServiceProvider();
var fileProvider = new TestFileProvider();
var webViewManager = new TestWebViewManager(services, fileProvider);
await webViewManager.AddRootComponentAsync(typeof(MyComponentWithInteractiveServerChild), "#app", ParameterView.Empty);

// Act - should not throw NotSupportedException
webViewManager.ReceiveAttachPageMessage();

// Assert
Assert.Collection(webViewManager.SentIpcMessages,
m => AssertHelpers.IsAttachWebRendererInteropMessage(m),
m => AssertHelpers.IsAttachToDocumentMessage(m, 0, "#app"),
m => AssertHelpers.IsRenderBatch(m));
}

@javiercn
javiercn force-pushed the copilot/fix-webviewrenderer-no-op-support branch from a2d599a to 931c719 Compare June 10, 2026 12:57
@javiercn
javiercn merged commit fb6e5b8 into main Jun 17, 2026
26 checks passed
@javiercn
javiercn deleted the copilot/fix-webviewrenderer-no-op-support branch June 17, 2026 09:21
@dotnet-milestone-bot dotnet-milestone-bot Bot added this to the 11.0-preview6 milestone Jun 23, 2026
kubaflo pushed a commit to dotnet/maui that referenced this pull request Aug 2, 2026
…r-web (#36484)

<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!

### Description

The **`maui-blazor-web`** (`maui-blazor-solution`) template shipped a
workaround that disabled per‑page/component interactivity in the shared
UI. In `template.json`, `InteractivityLocation` was a hardcoded
**generated constant** `"InteractiveGlobal"`, which forced
`InteractiveAtRoot` to always be `true` and therefore **stripped every
per‑page `@rendermode` directive** out of the shared components before
they reached the Hybrid‑consumed RCL. This existed only to avoid the
pre‑fix `NotSupportedException` thrown by the MAUI `BlazorWebView` when
a shared component carried an interactive render mode.


[dotnet/aspnetcore#65876](dotnet/aspnetcore#65876)
(shipped in **11.0‑preview6**, consumed by `net11.0` as
`11.0.0-preview.6.26325.125`) makes per‑page/component render modes a
**no‑op** inside `WebViewRenderer`, so the workaround is no longer
needed. This is **.NET 11 only** — hence this PR targets **`net11.0`**
(the fix is not in aspnetcore 10.0.0).

### What changed

1. **Restore `InteractivityLocation` as a real choice parameter**
(default `InteractivePerPage`, `isEnabled` when interactivity !=
`None`), re‑enabling per‑page interactivity and realigning with the
upstream ASP.NET Core **Blazor Web App** template (`BlazorWeb-CSharp` on
`dotnet/aspnetcore@main`, which is .NET 11). Adds the localization
strings and makes the location an IDE‑visible dropdown; on the CLI it
stays hidden and is driven by `--all-interactive` (matching upstream).
2. **Fix a latent collateral bug in the Web `_Imports.razor`.** The
`@using …Web.Components.Layout` import (needed for `<ReconnectModal />`)
was gated on `(… && InteractiveAtRoot)`, which was only equivalent to
the correct guard while the constant forced `InteractiveAtRoot` true.
With per‑page enabled it dropped the import for Server/Auto and produced
`RZ10012`. It is now `(UseServer && (!UseWebAssembly ||
!InteractiveAtRoot))` — intentionally **not** upstream's verbatim form,
because MAUI keeps only `ReconnectModal` in `Web/Components/Layout`
(NavMenu/MainLayout live in the shared RCL), so upstream's condition
would import an empty/nonexistent namespace in the WebAssembly/None
per‑page cases.
3. **Refresh `ReconnectModal` (razor/css/js) from upstream `main`.** The
Blazor **Server** reconnect UI (Web‑app only; never used in the Hybrid
app) was a stale copy. Syncing it brings the updated resume‑failure UX:
it now shows a dedicated "resume‑failed" state (`classList.replace`)
instead of forcing a `location.reload()`, the Resume button moves into
that state, and the copy/`&[open]` CSS are updated. ⚠️ *Behavioral
note:* this changes the Blazor Server reconnect experience for the
generated Web app.

The Web‑app `PageRenderMode` scaffolding (server‑only, gated behind
Individual auth which this template hardcodes off) and all other MAUI
adaptations were reviewed and **left untouched** — they are standard
Blazor Web scaffolding, not Hybrid workarounds.

> Note: `templatestrings.json` is committed in sync with
`templatestrings.en.json` (the templates build regenerates it as a
verbatim copy), matching the precedent of prior template PRs (#22234,
#34609) that touched this same file.

### Testing

Packed + installed the template into an isolated store and verified
generated output + `.Web` builds (with `-warnAsError`) across the full
CLI matrix on `net11.0`:

| `--interactivity` | `--all-interactive` | Shared `Counter` | Web root
| `.Web` build |
|---|---|---|---|---|
| None | — | excluded | static | ✅ |
| Server | off (default) | `@rendermode InteractiveServer` | static | ✅
|
| Server | on | none | `<Routes @rendermode="InteractiveServer"/>` | ✅ |
| WebAssembly | off | `@rendermode InteractiveWebAssembly` | static | ✅
|
| WebAssembly | on | none | `<Routes
@rendermode="InteractiveWebAssembly"/>` | ✅ |
| Auto | off | `@rendermode InteractiveAuto` | static | ✅ |
| Auto | on | none | `<Routes @rendermode="InteractiveAuto"/>` | ✅ |

Also built with orthogonal flags (`--empty`, `--use-program-main`,
`--no-https`, `--exclude-launch-settings`, `--localhost-tld`,
`--applicationId`, and all combined). The refreshed `ReconnectModal`
compiles in the Server/Auto variants. Hybrid platform builds are covered
by the existing `BlazorTemplateTest` integration tests (build both Web +
Hybrid on the matched workload); the Hybrid runtime no‑op on preview6
was verified separately in the Sandbox.

Incidentally, the `--interactivity None` case is now correct (a static
root), where the constant previously forced `InteractiveAtRoot` true.

### Added test coverage

`BlazorTemplateTest` is extended to guard the interactivity-location
behavior this PR re-enables:

- **`--all-interactive` build cases** (Server / WebAssembly / Auto)
added to `BuildMauiBlazorWebSolution`, which builds both the Web and
Hybrid projects with warnings-as-errors. The existing default cases
already exercise the new **per-page** default (and, via
warnings-as-errors, guard the `_Imports.razor` fix); these new rows
cover the previously untested **global** path — including the `Layout →
Web.Client` rename and `@using …Web.Client.Layout` import for WASM/Auto
at root.
- **A content-assertion test**
(`MauiBlazorWebEmitsInteractivityAtCorrectLocation`) that instantiates
the template and asserts the shared component carries `@rendermode`
per-page by default, and that `--all-interactive` moves the render mode
to the app root. A plain build cannot catch a regression here — the old
constant-based workaround built fine and only failed at runtime.

---------

Co-authored-by: Copilot App <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-blazor Includes: Blazor, Razor Components

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Blazor Hybrid (WebViewRenderer) should support per-page/component render modes as no-ops

4 participants