Skip to content

Latest commit

 

History

History
210 lines (146 loc) · 6.88 KB

dotnet-interop.md

File metadata and controls

210 lines (146 loc) · 6.88 KB

.NET interop

← Documentation index

Server-side rendering runs in-process, so .NET objects exposed to a view are real objects. Calls are synchronous and direct, with no await, no serialisation and no bridge.


Registering globals

builder.AddJsxCore(options =>
{
    options.Globals.Register<InventoryService>("Inventory");   // resolved from the request scope
    options.Globals.Register("Config", myConfigSingleton);     // one shared instance
    options.Globals.Register("Clock", sp => new Clock(sp));    // custom factory
});
Overload Lifetime
Register<TService>(name?) Resolved per render from the request's service scope
Register(name, instance) One shared instance, which must be thread-safe
Register(name, factory) Whatever your factory decides

The first two forms know what they registered, so the global arrives in TypeScript with its methods described. A factory returns object, so nothing can be said about it and a view sees any.

The declarations are generated by the build as well as by the running application, from registrations a source generator reads out of your project, so a view using a global type checks on a fresh clone. See how that works, and when it gives up.

Register<T>() defaults the name to the type name, so Register<InventoryService>() is exposed as InventoryService.


Calling them

Each registered global is a named export of dotnet:globals, typed from the C# it was registered as:

import { Inventory } from "dotnet:globals";

export default function Dashboard() {
    const lowStock = Inventory.getLowStock(20);

    return (
        <section>
            <p>Total: {Inventory.getTotalValue().toFixed(2)}</p>
            <ul>{lowStock.map((i) => <li key={i.sku}>{i.name}: {i.quantity}</li>)}</ul>
        </section>
    );
}

The C# behind it is completely ordinary. Nothing here knows about JavaScript:

public sealed class InventoryService
{
    public decimal GetTotalValue() => Items.Sum(i => i.Quantity * i.UnitPrice);
    public StockItem[] GetLowStock(int threshold) => Items.Where(i => i.Quantity <= threshold).ToArray();
}

Naming

Members are reachable under both their exact .NET name and a camelCase alias, so Greet() and greet() both work. Returned objects follow the same rule, which is why item.sku above resolves a C# property called Sku.

Turn the aliasing off if you would rather have one spelling:

options.ServerRendering.ExposeCamelCaseMembers = false;

Scoped services

Register<T>() resolves from the request scope, so a DbContext, the current user, or anything else scoped behaves as it would in a controller.


Typing the surface

dotnet is untyped, because it is a bag of whatever you registered. Cast at the use site, as above, or declare the shapes once in a .d.ts of your own and reuse them.

If your service types live in a Models namespace they are already generated for you, so you can often skip the hand-written interface:

import type MyApp from "dotnet:types";

const items = Inventory.getLowStock(20);   // already typed as MyApp.Models.StockItem[]

The escape hatch

dotnet is exported from the same module and reaches any global by name. It is what to use for one registered under a name that is not a valid identifier, or registered after startup:

import { dotnet } from "dotnet:globals";

const service = dotnet["my service"];

It is untyped, which is the trade: the named exports are generated from what was registered, and this is not.


Availability

.NET globals exist only during server rendering: RenderMode.Server, or the server pass of RenderMode.ServerAndClient.

Using one on the client throws with an explanatory message rather than failing silently. If a component runs in both modes, guard it:

import { Inventory } from "dotnet:globals";
import { isServerRender } from "dotnet:rendering";

const summary = isServerRender() ? Inventory.getSummary() : null;

Razor request-state helpers

Razor helpers that read per-request state have no direct equivalent, because the state lives in a .NET service and a view reaches those only by registration. Each one ports the same way: wrap the service in a class, register that as a global, call it from the view.

Antiforgery is the one every ported form needs:

public sealed class AntiforgeryTokens(IAntiforgery antiforgery, IHttpContextAccessor accessor)
{
    public string FieldName() => antiforgery.GetAndStoreTokens(accessor.HttpContext!).FormFieldName;
    public string Token() => antiforgery.GetAndStoreTokens(accessor.HttpContext!).RequestToken!;
}

builder.Services.AddHttpContextAccessor();
builder.Services.AddScoped<AntiforgeryTokens>();
builder.AddJsxCore(options => options.Globals.Register<AntiforgeryTokens>("Antiforgery"));
import { Antiforgery } from "dotnet:globals";

export function AntiforgeryField() {
    return <input type="hidden" name={Antiforgery.fieldName()} value={Antiforgery.token()} />;
}
Helper Reads Accessor to register
@Html.AntiForgeryToken() IAntiforgery IHttpContextAccessor
asp-validation-for, asp-validation-summary ModelState IActionContextAccessor

ModelState lives on the ActionContext rather than the HttpContext, which is why the second row needs a different accessor.

A view calling any of these has to be server-rendered: a client-rendered form carries no token, and its POST is rejected.


Security

Only what you register is reachable. JsxCore never enables the JavaScript engine's general CLR access, so a view cannot load arbitrary .NET types, touch the file system, or reach anything you did not explicitly hand it.

Server rendering also runs under limits:

options.ServerRendering.Timeout = TimeSpan.FromSeconds(5);    // wall clock per render
options.ServerRendering.MaxRecursionDepth = 256;

Treat a registered global the way you would treat a public API surface: a view is code, and a compromised view could call anything you exposed.


Why this is synchronous

Because the JavaScript engine runs in-process, a call into .NET returns immediately. There is no I/O boundary to await across. That removes the usual SSR dance of collecting promises and re-rendering, and it is why server components must be synchronous. An async component is rejected with an explicit error.

The endpoint is where await belongs, and it is ordinary async C#:

app.MapGet("/dashboard", async (InventoryService inventory) =>
    Results.Extensions.Jsx("Home/Dashboard", await inventory.LoadAsync()));

The view opens with "use server", which is what makes the globals reachable, so the endpoint says nothing about rendering.

See async endpoints.