RazorDocs Search

RazorWire

Namespaces

RazorWire

RazorWire is a library for building modern, reactive web applications in ASP.NET Core using an HTML-over-the-wire approach. It integrates seamlessly with the Runnable module system to provide real-time updates, reactive components ("Islands"), and enhanced form handling without the complexity of a full SPA framework.

Core Concepts

🏝️ Islands (Turbo Frames)

Islands are isolated regions of a page that can be loaded, reloaded, or updated independently. This is achieved using Turbo Frames, allowing you to decompose complex pages into smaller, manageable pieces.

📡 Real-time Streaming (Turbo Streams & SSE)

RazorWire uses Server-Sent Events (SSE) to push updates from the server to one or more clients. These updates are delivered as Turbo Streams, which can perform actions like append, prepend, replace, or remove on specific DOM elements.

⚡ Form Enhancement

Standard HTML forms are enhanced to perform partial-page updates. Instead of a full page reload or redirect, forms can return Turbo Stream actions to update only the necessary parts of the UI.

Security & Anti-Forgery

Handling Anti-Forgery tokens correctly is critical when updating forms via Turbo Streams. See Security & Anti-Forgery for detailed patterns and recommendations.

Getting Started

1. Add the Module

To enable RazorWire in your Runnable application, add the RazorWireWebModule to your root module or application startup:

public class MyRootModule : IRunnableWebModule
{
    public void RegisterDependentModules(ModuleDependencyBuilder builder)
    {
        builder.Add<RazorWireWebModule>();
    }
}

2. Configure Services (Optional)

You can customize RazorWire behavior via RazorWireOptions:

services.AddRazorWire(options => {
    options.Streams.BasePath = "/custom-stream-path";
});

3. Use in Controllers

Return reactive responses directly from your MVC controllers:

// Return an Island (Frame)
return RazorWireBridge.Frame(this, "my-island-id", "_PartialViewName", model);

// Return a Stream update
return this.RazorWireStream()
    .Append("chat-list", "<li>New Message</li>")
    .BuildResult();

Development Experience

RazorWire is designed for a fast feedback loop during development. When running in the Development environment:

  • Live Razor Views: Razor Runtime Compilation is automatically enabled, so you can edit .cshtml files and see changes on refresh without rebuilding.
  • Versioned Assets: Scripts and stylesheets referenced with local paths (e.g., ~/js/site.js) automatically receive version hashes for reliable cache busting, without needing asp-append-version="true".

API Reference

RazorWireBridge

  • Frame(controller, id, viewName, model): Returns a partial view wrapped in a <turbo-frame> with the specified ID.

IRazorWireStreamHub

The central hub for publishing real-time updates to connected clients.

  • PublishAsync(channel, content): Broadcasts a Turbo Stream fragment to all subscribers of a specific channel.

this.RazorWireStream() (Controller Extension)

A fluent API for building Turbo Stream responses:

  • Append(target, content): Adds content to the end of the target element.
  • Prepend(target, content): Adds content to the beginning.
  • Replace(target, content): Replaces the target element entirely.
  • Update(target, content): Replaces the inner content of the target.
  • Remove(target): Removes the target element.

TagHelpers

RazorWire provides several TagHelpers to simplify working with Turbo Frames and Streams in Razor views.

rw:island

Wraps content in a <turbo-frame>.

  • id: Unique identifier for the island.
  • src: URL to load content from (optional).
  • loading: Set to lazy for deferred loading.
  • permanent: Persists the element across page transitions.
<rw:island id="sidebar" src="/reactivity/sidebar" loading="lazy">
    <p>Loading sidebar...</p>
</rw:island>

rw:form

Enhances a standard form to return Turbo Stream updates.

  • target: The frame to target (optional).
<rw:form asp-action="Join" method="post">
    <input type="text" name="Username" />
    <button type="submit">Join</button>
</rw:form>

<time> (Local Time)

The <time> TagHelper provides a semantic way to render UTC timestamps that are automatically localized on the client side using the browser's Intl formatting APIs. This ensures that users see times in their own timezone and preferred format, with support for relative times (e.g., "5 minutes ago") that update automatically.

  • rw-type="local": Opt-in attribute to enable RazorWire local time formatting.
  • rw-display: Display mode. Valid values: time (default), date, datetime, or relative (auto-updating).
  • rw-format: Format style for absolute modes. Valid values: short, medium (default), long, or full.
<!-- Relative auto-updating time (e.g., "5 minutes ago") -->
<time datetime="@Model.Timestamp" rw-type="local" rw-display="relative"></time>

<!-- Short local date/time -->
<time datetime="@Model.Timestamp" rw-type="local" rw-display="datetime" rw-format="short"></time>

rw:scripts

Injects necessary RazorWire and Turbo client scripts.

<rw:scripts />

Utilities

StringUtils

Provides safe identifier generation for DOM elements and URL anchors.

  • ToSafeId(input, appendHash): Sanitizes strings by replacing non-alphanumeric characters with hyphens and collapse consecutive hyphens. Optionally appends a deterministic hash for uniqueness.

Client-Side Interop (Hybrid Components)

RazorWire supports a hybrid approach where server-rendered "Islands" can be augmented with client-side modules (e.g., React, Vue, or Vanilla JS).

  • client-module: The name of the JavaScript module to initialize.
  • client-strategy: Initialization strategy (e.g., load, idle, visible).
  • client-props: JSON properties passed to the client module.
<rw:island id="interactive-chart" 
           client-module="ChartComponent" 
           client-strategy="visible" 
           client-props='{ "data": [1, 2, 3] }'>
</rw:island>

Static Export

RazorWire can be used to generate static or hybrid sites. For more details, see the RazorWire CLI.

Examples

For a practical demonstration of these features, see the RazorWire MVC Example.

Type

RazorWireWebModule

A web module that integrates RazorWire real-time streaming and output caching into the application.

Method

ConfigureWebOptions

void ConfigureWebOptions(StartupContext context, WebOptions options)

Ensures the application's MVC support level is at least ControllersWithViews.

Parameters

  • contextThe startup context for the web module.
  • optionsWeb options to configure; may be modified to raise Mvc.MvcSupportLevel to ControllersWithViews if it is lower.
Method

ConfigureServices

void ConfigureServices(StartupContext context, IServiceCollection services)

Registers RazorWire services, enables output caching, and configures output cache options to include RazorWire policies.

Parameters

  • contextThe startup context for the current module initialization.
  • servicesThe service collection to which RazorWire, output caching, and related options are added.
Method

RegisterDependentModules

void RegisterDependentModules(ModuleDependencyBuilder builder)

Registers this module's dependencies with the provided dependency builder.

Parameters

  • builderThe dependency builder used to declare other modules this module requires.
Method

ConfigureHostBeforeServices

void ConfigureHostBeforeServices(StartupContext context, Microsoft.Extensions.Hosting.IHostBuilder builder)

Executes module-specific host configuration before application services are registered.

Parameters

  • contextThe startup context providing environment and configuration for module initialization.
  • builderThe host builder to apply pre-service host configuration to.

Remarks

The default implementation does nothing.

Method

ConfigureHostAfterServices

void ConfigureHostAfterServices(StartupContext context, Microsoft.Extensions.Hosting.IHostBuilder builder)

Provides a hook to modify the host builder after services have been registered.

Parameters

  • contextStartup context containing environment and module information.
  • builderThe Microsoft.Extensions.Hosting.IHostBuilder to configure.
Method

ConfigureWebApplication

void ConfigureWebApplication(StartupContext context, IApplicationBuilder app)

Enables output caching in the application's request pipeline.

Parameters

  • contextStartup context providing environment and configuration for module initialization.
  • appApplication builder used to configure the HTTP request pipeline.
Method

ConfigureEndpoints

void ConfigureEndpoints(StartupContext context, IEndpointRouteBuilder endpoints)

Maps RazorWire HTTP endpoints into the application's endpoint route builder.

Parameters

  • contextThe startup context providing environment and configuration for module initialization.
  • endpointsThe endpoint route builder to which RazorWire routes will be added.
Property

IncludeAsApplicationPart

bool IncludeAsApplicationPart { get; }

Gets a value indicating whether this module's assembly should be searched for MVC application parts. Returns true for RazorWire to enable its tag helpers and other components.

Type

ExampleJsInterop

Provides an example of how JavaScript functionality can be wrapped in a .NET class for easy consumption.

Parameters

  • jsRuntimeThe JS runtime used to invoke JavaScript functions.
Method

Prompt

ValueTask<string?> Prompt(string message)

Shows a browser prompt dialog with the specified message and returns the user's input as a string, or null if the dialog was dismissed.

Parameters

  • messageThe message to display in the prompt dialog.

Returns

The user's input as a string, or null if the dialog was dismissed.

Method

DisposeAsync

ValueTask DisposeAsync()

Disposes the loaded JavaScript module and releases associated JS resources.

Remarks

If the module was never loaded, this method completes without action.

Type

RazorWireOptions

Represents configuration options for the RazorWire real-time streaming and caching system.

Property

Default

RazorWireOptions Default { get; }

Gets a default instance of RazorWireOptions with default configuration settings.

Property

Streams

RazorWireStreamOptions Streams { get; }

Gets configuration options for real-time streams, such as the base path for stream connections.

Property

Caching

RazorWireCacheOptions Caching { get; }

Gets configuration options for output caching policies used by RazorWire.

Type

RazorWireStreamOptions

Represents configuration options for RazorWire real-time streams.

Property

BasePath

string BasePath { get; set; }

Gets or sets the base path used for establishing stream connections. Defaults to "/_rw/streams".

Type

RazorWireCacheOptions

Represents configuration options for RazorWire output caching.

Property

PagePolicyName

string PagePolicyName { get; set; }

Gets or sets the name of the output cache policy for full pages. Defaults to "rw-page".

Property

IslandPolicyName

string IslandPolicyName { get; set; }

Gets or sets the name of the output cache policy for individual islands. Defaults to "rw-island".

Type

RazorWireEndpointRouteBuilderExtensions

Provides extension methods for IEndpointRouteBuilder to map RazorWire endpoints.

Method

MapRazorWire

IEndpointRouteBuilder MapRazorWire(this IEndpointRouteBuilder endpoints)

Registers a Server-Sent Events (SSE) GET endpoint at the configured streams base path that streams messages for a named channel.

Parameters

  • endpointsThe endpoint route builder to configure.

Returns

The original IEndpointRouteBuilder instance.

Remarks

The endpoint enforces channel subscription authorization, streams hub messages as SSE (each line emitted as a `data:` event), sends a 20-second heartbeat comment when idle, and unsubscribes on client disconnect.

Type

StringUtils

Provides utility methods for string manipulation, specifically for generating safe identifiers.

Method

ToSafeId

string ToSafeId(string? input, bool appendHash = false)

Produces a safe identifier by replacing disallowed characters with hyphens, collapsing consecutive hyphens, trimming edge hyphens, and defaulting to "id" for null, whitespace, or empty results. Optionally appends a short deterministic 4-character lowercase hex hash (prefixed with a hyphen) derived from the original input to ensure uniqueness.

Parameters

  • inputThe source string to convert into a safe identifier.
  • appendHashIf true, appends a short deterministic 4-character lowercase hex hash (prefixed with a hyphen).

Returns

The sanitized identifier; if appendHash is true the value is suffixed with "-" and a 4-character lowercase hex hash.

Method

GetDeterministicHash

string GetDeterministicHash(string input)

Produces a short deterministic 4-character lowercase hexadecimal string derived from the SHA-256 hash of the input.

Parameters

  • inputThe string to hash.

Returns

A 4-character lowercase hexadecimal string.

Remarks

Returns only the first 4 hex characters (16 bits) of the SHA-256 digest; collisions are possible.

Type

RazorWireControllerExtensions

Provides extension methods for MVC controllers to interact with RazorWire.

Method

RazorWireStream

RazorWireStreamBuilder RazorWireStream(this Controller controller)

Creates a RazorWireStreamBuilder bound to the specified controller.

Parameters

  • controllerThe controller instance used to initialize the builder.

Returns

A RazorWireStreamBuilder configured to operate with the given controller.

Type

RazorWireServiceCollectionExtensions

Provides extension methods for registering RazorWire services into the IServiceCollection.

Method

AddRazorWire

IServiceCollection AddRazorWire(this IServiceCollection services, Action<RazorWireOptions>? configure = null)

Registers RazorWire options and default RazorWire services, including IRazorPartialRenderer, into the provided IServiceCollection.

Parameters

  • servicesThe service collection to register RazorWire services into.
  • configureOptional action to configure RazorWireOptions; if null, default options are used.

Returns

The same IServiceCollection instance with RazorWire registrations added.