Blazor.AutoGen
0.1.0-preview.13
dotnet add package Blazor.AutoGen --version 0.1.0-preview.13
NuGet\Install-Package Blazor.AutoGen -Version 0.1.0-preview.13
<PackageReference Include="Blazor.AutoGen" Version="0.1.0-preview.13" />
<PackageVersion Include="Blazor.AutoGen" Version="0.1.0-preview.13" />
<PackageReference Include="Blazor.AutoGen" />
paket add Blazor.AutoGen --version 0.1.0-preview.13
#r "nuget: Blazor.AutoGen, 0.1.0-preview.13"
#:package Blazor.AutoGen@0.1.0-preview.13
#addin nuget:?package=Blazor.AutoGen&version=0.1.0-preview.13&prerelease
#tool nuget:?package=Blazor.AutoGen&version=0.1.0-preview.13&prerelease
Blazor.AutoGen
Write Blazor Interactive Auto service logic once. You write an interface and a server
implementation. A source generator writes the WebAssembly HttpClient proxy, the API endpoints
and the DI registrations.
Docs:
- How it works and why: architecture, generated code, design decisions, findings.
- Testing and benchmarks: what the 429 tests cover, and the performance numbers.
- Publishing to NuGet: for maintainers.
- Changelog.
Contents:
- Overview: Features
- Getting started: The problem · Quick start · Adding it to an existing app · Opt in per method · Routes · HTTP methods
- Auth and HTTP: Authorization and the current user · Your own HttpClient · .NET MAUI Blazor Hybrid · Intercepting calls · Returning errors · Cookies and token refresh · Thread safety
- JSON and DI: JSON on the wire · Smaller responses · Registering services yourself
- Reference: How it works · Where the generated code lives · Rules the generator checks · Limitations · Performance · Sample · Requirements · Contributing · License
Features
Everything below is generated at build time from your [Remote] interfaces. Features marked
new arrived in 0.1.0-preview.6 or later; opt-in ones are off until you turn them on.
Write the service once
- One contract, both sides. You write an interface and a server class. The generator writes
the WebAssembly
HttpClientproxy, the API endpoints and the DI registrations for both projects. Quick start - Nothing generated to commit. The generated code is produced by the compiler on every build and never lands in your repository; your IDE shows it read-only. Where the generated code lives
- Same code in every render mode. On the server, components get your real service in-process; in WebAssembly they get the proxy. The component doesn't change. How it works
- Server-only methods stay server-only. Put
[Remote]on single methods instead of the interface; the others get no endpoint and throw if called from WebAssembly. Opt in per method - Contracts anywhere. Interfaces can live in the
.Clientproject or a shared library, and the projects that reference them generate the code. How it works - Every Blazor host. WebAssembly, .NET MAUI, WPF and WinForms Blazor Hybrid, and any .NET app with DI. Blazor Hybrid
HTTP the way you want it
- Routes your way. Default
_remote/...routes, a route per interface or method, or oneRemoteConventionline that matches your controllers' naming. Overloads get their own routes. Routes - Every HTTP method (new).
[Remote(Method = RemoteHttpMethod.Get)]and Put, Patch, Delete. POST, PUT and PATCH send a JSON body; GET and DELETE send the parameters in the query string, formatted so they arrive exactly as sent (dates, enums, decimals, arrays and lists). HTTP methods - HTTP methods from method names (new, on by default).
GetAsyncis a GET,DeleteAsynca DELETE,UpdateAsynca PUT andPatchAsynca PATCH with nothing to set up; a method stays POST when its parameters can't go in a query string or include a collection, and one line turns it off. Methods from names - Correct HTTP errors. 400 for bad input, 415 for a body that isn't JSON, and 405 with an
Allowheader for the wrong HTTP method (new), even in apps that turn errors into HTML pages. 400 and 415 come as problem details saying what was wrong, and the client puts thedetailof any problem details response into its exception message (new). Returning errors - Smaller responses (new, opt-in).
AddRemoteServices(compressResponses: true)sends large responses Brotli- or gzip-compressed, about 80% smaller for typical lists. Smaller responses
Security and the request pipeline
- Your auth, unchanged.
[Authorize], roles and policies on the interface or the implementation, with Identity cookies, JWT bearer or any scheme. Signed-out calls get 401, not a redirect, and your service sees the user throughAuthenticationStateProvider. Authorization - CSRF protection for GET and DELETE (new, on by default). A link, form,
<img>or<script>on another site gets 403 instead of calling the endpoint with the user's cookies; the generated client and CORS fetches pass.AddRemoteServices(refuseCrossSiteRequests: false)turns it off. HTTP methods - Call filters.
IRemoteCallFilterwraps every proxy call like middleware: change arguments, add headers, retry, short-circuit, log. Intercepting calls, Logging errors - Your own
HttpClient. NamedIHttpClientFactoryclients,DelegatingHandlers, Polly, timeouts and token refresh work as they are. Your own HttpClient, Cookies and token refresh - Cancellation. A
CancellationTokenparameter cancels the HTTP call on the client and becomesRequestAbortedon the server. How it works
JSON
- JSON you control. System.Text.Json on the wire, separate from your app's JSON settings, and configured once for both sides. Newtonsoft-based MVC controllers can live next to it. JSON on the wire
Safety and speed
- Mistakes fail the build. 19 diagnostics point at the exact line: duplicate routes, clashes with controller actions, types that won't survive JSON, GET parameters that can't go in a query string, and more. Rules the generator checks
- Per-project switch.
<BlazorAutoGenEnabled>false</BlazorAutoGenEnabled>keeps a project to diagnostics only. Adding it to an existing app - As fast and as small as hand-written code. Calls are within a few percent of a hand-written
client. In the WebAssembly download the generated code costs about 6 KB plus 58 bytes per method:
a little more than the leanest hand-written client, and less than one-
async-method-per-call clients once an app has about 80 methods. The generator stays cached while you type. Performance
The problem
With @rendermode InteractiveAuto, a component runs on the server first, then in the browser
on WebAssembly. In the browser it can't reach your database, so today every service needs:
- an interface,
- a server implementation,
- a client implementation that calls the API with
HttpClient, - an API endpoint that forwards to the server implementation,
- a DI registration in the server
Program.cs, and another in the clientProgram.cs.
Items 3 to 5 are boilerplate that must be kept in sync by hand. The Blazor team tracks this as dotnet/aspnetcore#60312, and Blazor going into 2027 describes how much it costs in practice. Blazor.AutoGen generates items 3 to 5.
Quick start
1. Add the package to both projects (the server project and the .Client project).
The generator also runs in projects that only get the package through a project reference, so
the server would pick it up from .Client; a reference in each project keeps the version
explicit.
dotnet add package Blazor.AutoGen --prerelease
or in the .csproj:
<PackageReference Include="Blazor.AutoGen" Version="0.1.0-preview.13" />
The package was called InteractiveAutoCodeGen up to 0.1.0-preview.1. If you used that one,
replace the package reference and change using InteractiveAutoCodeGen; to
using Blazor.AutoGen;. See the changelog for the other renamed names.
2. Mark an interface in the .Client project with [Remote].
using Blazor.AutoGen;
using Microsoft.AspNetCore.Authorization;
[Remote]
public interface IWeatherService
{
Task<WeatherForecast[]> GetForecastAsync(int days, CancellationToken cancellationToken = default);
[Authorize]
Task<string> GetSignedInUserAsync();
}
3. Implement it once, in the server project.
public class WeatherService(AppDbContext db, AuthenticationStateProvider auth) : IWeatherService
{
// real logic: database, files, secrets...
}
4. Add three lines.
// .Client/Program.cs
builder.Services.AddRemoteClients();
// Server Program.cs
builder.Services.AddRemoteServices(); // registers WeatherService as IWeatherService
app.MapRemoteServices(); // maps the /_remote/... endpoints
5. Inject the interface anywhere.
@rendermode InteractiveAuto
@inject IWeatherService WeatherService
On the server (prerendering, Interactive Server) the call goes straight to WeatherService, with
no HTTP. In WebAssembly it goes through the generated proxy. The component doesn't know the
difference.
Adding it to an existing app
Add [Remote] to the interface, then delete the hand-written client service, endpoint and
registrations. These points came out of trying it on a large production app:
Remove the old client registration.
AddRemoteClients()usesTryAddScoped, so an interface that is already registered keeps its hand-written client and the proxy is never used.Interfaces in a shared library that references DI (a Razor class library, say) make the generator emit unused proxies into that library, which then ship to the browser. Turn generation off there and keep only the diagnostics. Neither
ExcludeAssets="analyzers"norPrivateAssets="analyzers"keeps a package's generator out of a project, so use this:<PropertyGroup> <BlazorAutoGenEnabled>false</BlazorAutoGenEnabled> </PropertyGroup>Other apps that reference that library get the generator too, through the project reference, for example a MAUI or WPF app that keeps its own hand-written clients. They get proxies that nothing registers unless the app calls
AddRemoteClients. Set the same property in those projects to leave them out. It works there from 0.1.0-preview.5; earlier versions only read it in projects that reference the package directly.Test projects that reference the server (with
WebApplicationFactory, say) get the generator the same way. Set the property there too: they then report no BAG009 for having two fakes of one interface (since 0.1.0-preview.12), and generate nothing.Middleware matched on
/api/*doesn't see the endpoints, which live under/_remote/. That includes IP rate limiting rules such as AspNetCoreRateLimit's*:/api/*. Either add the same rules for/_remote/*, or move the endpoints under your API prefix with[assembly: RemoteConvention("api/remote/[service]/[method]")](see Routes).Clients that returned
nullon failure. A proxy throwsHttpRequestExceptionwith the status code, for example on a 401 when a session expires. If your components expectnull, returndefaultfrom anIRemoteCallFilterthat catchesHttpRequestException.Check what each old client method caught, one by one. A filter applies to every call, but hand-written clients often differ per method: reads let a timeout through while a save swallows everything. A caller with no
try/catchthen crashes on the first network error. Give such a method its own clause, keyed oncontext.InterfaceNameandcontext.MethodName:catch (Exception) when (context.InterfaceName == typeof(ICartService).FullName && context.MethodName == nameof(ICartService.SaveAsync)) { return null; // the old client returned null on any failure }Renaming a parameter is a breaking change for installed clients. Parameters travel by name. A client built before the rename (a cached WebAssembly bundle, a MAUI app) sends the old name and gets a 400 whose message names it, instead of the server silently getting
nullor0(since 0.1.0-preview.12). Keep parameter names stable once a client has shipped.Pin the routes of overloads once a client has shipped. An overload's default route ends in its parameter names, so renaming a parameter moves the endpoint, and installed apps (MAUI, a cached WebAssembly bundle) get 404. Give each overload a fixed route with
[Remote("...")](see Routes).[Authorize]goes on the interface methods, or on the implementation class. C# doesn't allow it on an interface.
Opt in per method
Put [Remote] on individual methods instead of the interface. Unmarked methods get no
endpoint and throw NotSupportedException if they're called from WebAssembly, so server-only
operations are never exposed.
public interface IOrderService
{
[Remote] Task<OrderDto[]> GetMyOrdersAsync();
Task PurgeOldOrdersAsync(); // server only
}
Routes
By default each method is _remote/{Namespace.IInterface}/{Method}, with the HTTP method its name
picks (see HTTP methods). You can name routes
per interface, per method, or for a whole project, and choose the HTTP method (see
HTTP methods):
[Remote("api/orders")] // the whole interface under api/orders
public interface IOrderService
{
Task<Order[]> ListAsync(); // POST api/orders/ListAsync
[Remote("recent")] // POST api/orders/recent (relative)
Task<Order[]> RecentAsync();
[Remote("/api/v2/orders/export")] // POST api/v2/orders/export (leading '/': absolute)
Task<byte[]> ExportAsync();
}
Match your controllers' naming. Put one line in the project that declares the interfaces
(usually .Client):
[assembly: RemoteConvention("api/[service]/[method]", Casing = RemoteRouteCasing.KebabCase)]
// IWeatherService.GetForecastAsync -> POST api/weather/get-forecast
[service]is the interface name without the leadingIand a trailingService.[method]is the method name withoutAsync, as MVC does for actions.[controller]and[action]work as aliases.CasingisAsIs,LowerCaseorKebabCase, andStripAsyncSuffix = falsekeepsAsync.HttpMethods = RemoteHttpMethods.Postmakes every method POST unless it says otherwise, instead of letting method names pick; see HTTP methods.- Interface and method routes still override the convention.
The server generator reads your MVC controllers. When they follow a pattern and the remote
endpoints don't, it reports BAG014 (info) with the exact line to add. For example, for
controllers routed api/[controller] it suggests
[assembly: RemoteConvention("api/[service]/[method]")].
It can't apply the pattern silently. The client and the server must compute the same URL, and the client project never sees the server's controllers. So the convention lives in the project both of them compile against.
Overloads get a route each, by appending their parameter names: FindAsync(string name) maps
to .../FindAsync-name, and FindAsync(int id, int page) to .../FindAsync-id-page (or
find-name and find-id-page under a kebab-case convention). Give an overload its own name with
[Remote("...")] if you prefer. Do that for any overload an installed app calls: with the default
route, renaming a parameter changes the URL.
Duplicates are build errors. These all fail the build, pointing at the method to fix:
- BAG011: two remote endpoints with the same route and HTTP method, routes compared
case-insensitively and ignoring a trailing
/, as ASP.NET Core does. This includes interfaces from other projects and overloads whose parameter names match. - BAG012: a remote endpoint with the same route as an action on one of your controllers that
accepts the same HTTP method. The check understands
[Route](including an inherited one),[HttpGet],[HttpPost],[HttpPut],[HttpPatch],[HttpDelete],[AcceptVerbs], actions with no verb attribute (they take any method),[controller]/[action]tokens, absolute~/and/templates and[NonAction]/[NonController]. - BAG013: a route that isn't a literal path.
Name clash: MVC has its own
[Remote]attribute, for remote validation. In a file that imports bothMicrosoft.AspNetCore.MvcandBlazor.AutoGen,[Remote]is ambiguous (CS0104). Interfaces usually live in.Client, which doesn't use MVC. If yours don't, addusing RemoteAttribute = Blazor.AutoGen.RemoteAttribute;to that file.
HTTP methods
By default each method's name picks its HTTP method: GetAsync is a GET, DeleteAsync a DELETE,
UpdateAsync a PUT, anything without a matching word a POST
(details below). To choose yourself, set Method on [Remote], on the
interface (the default for its methods) or on a method (which wins):
[Remote("api/products", Method = RemoteHttpMethod.Get)] // every method is a GET unless it says otherwise
public interface IProductService
{
Task<Product[]> SearchAsync(string? text, int page, Category[] categories);
// GET api/products/SearchAsync?text=pen&page=2&categories=Office&categories=Art
[Remote(RemoteHttpMethod.Get, "item")] Task<Product?> GetAsync(int id); // GET api/products/item?id=5
[Remote(RemoteHttpMethod.Delete, "item")] Task DeleteAsync(int id); // DELETE api/products/item?id=5
[Remote(RemoteHttpMethod.Put, "item")] Task SaveAsync(int id, Product product); // PUT api/products/item, JSON body
[Remote(RemoteHttpMethod.Patch, "item")] Task RenameAsync(int id, string name); // PATCH api/products/item, JSON body
[Remote(Method = RemoteHttpMethod.Post)] Task<int> ImportAsync(Product[] products); // POST, JSON body
}
Where the parameters go:
| Method | Parameters | Parameter types |
|---|---|---|
| POST (default), PUT, PATCH | one JSON object in the body, as before | anything System.Text.Json can send |
| GET, DELETE | the query string, one name=value per parameter |
simple values only, see below |
GET and DELETE parameters must be a string, bool, char, any integer type, float,
double, decimal, an enum, Guid, DateTime, DateTimeOffset, DateOnly, TimeOnly or
TimeSpan. Nullable versions are allowed, and so are arrays and lists of the non-nullable ones
(T[], List<T>, IEnumerable<T>, IReadOnlyList<T>, IReadOnlyCollection<T>, IList<T>,
ICollection<T>). Anything else is a build error (BAG016) that tells you to use POST, PUT or
PATCH.
How values travel, so that other clients (a browser, curl, another service) can call the endpoints too:
- Values use the invariant culture and come back exactly: numbers as
1234.5, dates and times in ISO 8601 (2026-11-29,13:45:30.1234567,DateTimekeeps itsKind),TimeSpanas-3.00:00:00, enums by name (Blue, flags asRead, Write; a number is accepted too). - Names are the parameter names, compared case-insensitively. Values are URL-encoded.
- A
nullvalue is left out and arrives asnull. An empty string stays an empty string. - A collection repeats its name once per item:
ids=1&ids=2. Anullor empty collection arrives as an empty one, and anullstring inside a collection throwsArgumentExceptionon the client before anything is sent. - A missing required value, a value that doesn't parse, or a single-value parameter given twice
gets 400. Calling an endpoint with another HTTP method gets 405 with an
Allowheader listing the methods the route takes, also in apps that turn errors into pages withUseStatusCodePagesWithReExecute, as the Blazor template does. Your own endpoints on the same path (a controller's GET, say) still win for their methods.
IRemoteCallFilters work the same for every method: context.Request.Method tells them which one,
and changes to context.Arguments end up in the query string. A query the filter adds to
context.Request.RequestUri is kept, and the arguments are appended after it.
Keep query strings short. Servers and proxies limit URL length (Kestrel allows a request line of 8 KB by default), so send long lists or large text with POST.
Different methods can share a route, like item above. BAG011 only fails the build for two
endpoints with the same route and method, and BAG012 checks controllers per method.
Choosing the HTTP method from the method name (the default)
Check your read-named methods: with cookie authentication, a browser sends cookies along with a GET that another site starts (a link or a redirect). A method named like a read but that changes data, such as
GetOrCreateCartAsync, becomes something another site can trigger. Give such methods[Remote(Method = RemoteHttpMethod.Post)], or another name.GET and DELETE endpoints also refuse those requests themselves (since 0.1.0-preview.13): a request a browser marks as cross-site (
Sec-Fetch-Site: cross-siteorsame-site) that isn't a CORSfetch(Sec-Fetch-Modeother thancors) gets 403. The generated client, CORS fetches from your other origins, a URL typed into the address bar and non-browser clients still get through. Browsers without Fetch Metadata headers (older than 2023) aren't covered, so the advice above still stands. If other sites must reach these endpoints with plain links or embeds, and no GET or DELETE method changes data, turn the check off withbuilder.Services.AddRemoteServices(refuseCrossSiteRequests: false).
With nothing to set up, the first word of each method's name picks its HTTP method:
| Name starts with | HTTP method |
|---|---|
Get, Find, List, Search, Count, Fetch, Load |
GET, if every parameter is a single simple value |
Delete, Remove |
DELETE, with the same condition |
Update, Replace |
PUT |
Patch |
PATCH |
anything else (Create, Add, Save, Send...) |
POST |
A word only counts when the name continues with an uppercase letter, a digit or
_, or ends there:GetAsyncandListAllmatch,GetawayandListendon't.GetOrdersAsync(OrderFilter filter)stays POST, because the filter can't go in a query string. The build reports BAG017 (info) on that parameter, so it's never a mystery why.GetByIdsAsync(List<Guid> ids)stays POST too (since 0.1.0-preview.12), also with BAG017. A collection fits in a query string, but a few hundred ids make the URL longer than servers accept (Kestrel's limit is 8 KB), and that would only fail with real data. Set[Remote(Method = RemoteHttpMethod.Get)]on the method if its lists are always short.A
Methodon the method or on its interface always wins over the name.Turning it off: one line in the project that declares the interfaces (usually
.Client) makes every method POST unless it says otherwise, as before 0.1.0-preview.9:[assembly: RemoteConvention(HttpMethods = RemoteHttpMethods.Post)]Upgrading from 0.1.0-preview.8 or earlier: endpoints of matching methods change from POST to GET, PUT, PATCH or DELETE. Deploy the server and the WebAssembly app together, as for any route change (a WebAssembly app still cached in a browser gets 405 until it reloads), or add the line above to keep POST.
PUT, PATCH or DELETE get 405 or 403 in production but work locally? Something in front of the app refuses those methods. On IIS that's usually the WebDAV module; remove it in
web.config:<system.webServer> <modules><remove name="WebDAVModule" /></modules> <handlers><remove name="WebDAV" /></handlers> </system.webServer>Some firewalls and corporate proxies also allow only GET and POST. If you can't change them, use the line above to keep every method POST.
Authorization and the current user
The generated endpoints are ordinary ASP.NET Core endpoints, so they use whatever authentication and authorization your app already has. You don't need to configure anything extra for the generator.
Where you can put authorization:
| Where | Example | Applies to |
|---|---|---|
| Interface method | [Authorize(Roles = "admin")] Task<X> M(); |
that method |
| Implementation class | [Authorize] public class OrderService : IOrderService |
every method, like a controller |
| Implementation method | [Authorize(Policy = "Adult")] public Task<X> M() |
that method |
| Route group | app.MapRemoteServices().RequireAuthorization("Staff"); |
every remote endpoint |
| Fallback policy | options.FallbackPolicy = ...RequireAuthenticatedUser()... |
every endpoint without its own rule |
[AllowAnonymous] works in any of these places and wins over the others, just as it does for
controllers. C# doesn't allow [Authorize] on an interface itself, so put it on the
implementation class instead. Attributes on the implementation are read from the class that is
actually registered for the interface when MapRemoteServices() runs, so a class in another project
or one you register yourself works too (since 0.1.0-preview.12). Two cases fall back to the class
the generator found in the server project: a registration made with a factory, and an app that
doesn't call AddRemoteServices(). The app logs a warning at startup for both: one for each
interface registered with a factory, and a single one for the app when AddRemoteServices() wasn't
called (since 0.1.0-preview.13). In those, put the attributes on the interface methods or the route
group instead.
What's tested (tests/Blazor.AutoGen.Tests/AuthTests.cs):
- No auth at all: apps without
AddAuthenticationorAddAuthorizationwork. An[Authorize]method then fails with a 500 instead of running unprotected; that check is ASP.NET Core's own. - Cookie auth (including ASP.NET Core Identity): signed out gives 401 and wrong role gives 403, never a 302 to the login or access-denied page.
- JWT bearer: valid, invalid and missing tokens, plus role claims.
- Multiple schemes: cookie by default with
[Authorize(AuthenticationSchemes = "Bearer")]where asked, or a default policy that accepts either scheme. - Roles, policies, fallback policy, group conventions, and
[AllowAnonymous]overrides.
The current user inside a service: inject AuthenticationStateProvider. The generated
endpoint hands it the request's user, so the same code works in-process and over HTTP. This is
tested with the template's IdentityRevalidatingAuthenticationStateProvider.
When signed out, the proxy throws HttpRequestException with StatusCode set to 401 or 403.
Important: authorization protects the HTTP endpoint. In-process calls (prerendering, Interactive Server) don't go through it. Keep
[Authorize]on your pages, or check the user inside the service when it matters.
Your own HttpClient
In a WebAssembly project the proxies default to an HttpClient pointed at the app's base address.
Elsewhere (Blazor Hybrid, console, tests) the factory is required. To use your own,
pass a factory. It's called once per DI scope, so the whole WebAssembly app shares one client:
// A named IHttpClientFactory client with its own handlers, timeout or base address
builder.Services.AddHttpClient("remote", c => c.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress))
.AddHttpMessageHandler<TokenHandler>();
builder.Services.AddRemoteClients(httpClient: sp => sp.GetRequiredService<IHttpClientFactory>().CreateClient("remote"));
// Or reuse an HttpClient you already registered
builder.Services.AddRemoteClients(httpClient: sp => sp.GetRequiredService<HttpClient>());
Default headers, Timeout, DelegatingHandlers (Polly, logging, auth) and a base address with a
path (https://host/api/v2/) all apply. Tests in HttpClientTests.cs cover each of these.
The default client is a plain new HttpClient() per DI scope, which never gets disposed. That's
right in WebAssembly, where the browser does the networking and there is one scope. In a long-running
process with many scopes, pass an IHttpClientFactory client as above, so connections are pooled
and DNS changes are picked up.
.NET MAUI Blazor Hybrid (and WPF / WinForms)
A hybrid app runs your Razor components in a native WebView, so its UI is shared with the web app
while the service logic still lives on the server. Use the dotnet new maui-blazor-web layout:
| Project | Package | What you write |
|---|---|---|
App.Shared (Razor class library) |
yes | the [Remote] interfaces and the pages that inject them |
App.Web (server) |
yes | the implementations, AddRemoteServices(), MapRemoteServices() |
App.Web.Client (WebAssembly) |
yes | AddRemoteClients() |
App (MAUI) |
yes | AddRemoteClients(httpClient: ...) with the server's address |
// MauiProgram.cs
builder.Services.AddMauiBlazorWebView();
builder.Services.AddRemoteClients(_ => new HttpClient { BaseAddress = new Uri("https://api.example.com/") });
Inside a WebView, NavigationManager.BaseUri is the WebView's own address (https://0.0.0.0/),
not your server. So in a hybrid project the httpClient argument is required, and leaving it out
is a compile error (CS7036) rather than calls that go nowhere.
- Signing in: the app has no browser cookie for your site. Send a bearer token from a
DelegatingHandler(or anIRemoteCallFilter), and accept it on the server withAddAuthentication().AddJwtBearer()next to the cookie scheme. Make sure the policy authenticates that scheme too (for example[Authorize(AuthenticationSchemes = "Identity.Application,Bearer")]or a policy that lists both); then[Authorize]andAuthenticationStateProviderwork as for the web app.JwtBearerTestscovers the server side. - Local development: the Android emulator reaches your machine at
10.0.2.2, notlocalhost, and Android and iOS block plainhttp://unless you allow it. Use the HTTPS address with a trusted dev certificate, or allow cleartext for debug builds only. - Offline or on-device logic: register your own implementation before
AddRemoteClients(). Existing registrations win, so the app calls it in-process. - Trimming: the wire format uses reflection-based System.Text.Json, so NativeAOT isn't
supported, and trimmed Release builds haven't been tested yet. If a trimmed build loses DTO
members, keep your DTO assembly with
<TrimmerRootAssembly Include="App.Shared" />.
This was checked with a real maui-blazor-web app on .NET 11: the MAUI Windows app's page called
the web server's generated endpoint (200), and the app builds for Android and Windows. iOS and Mac
Catalyst use the same generated code but weren't built here (they need a Mac).
Intercepting calls (IRemoteCallFilter)
Filters run around every proxy call, like middleware, in the order you register them, with any DI lifetime. A filter can:
- change the arguments before they're serialized,
- set headers or request options,
- skip the server and return a value of its own,
- change the result, catch exceptions, retry, or replace the cancellation token.
public sealed class StampFilter(TimeProvider clock) : IRemoteCallFilter
{
public async Task<object?> InvokeAsync(RemoteCallContext context, RemoteCallDelegate next)
{
// context.InterfaceName, MethodName, ParameterNames, Arguments, ResultType, Request, Services, Items
if (context.MethodName == "SaveAsync" && context["order"] is OrderDto order)
context["order"] = order with { ClientTime = clock.GetUtcNow() }; // change what is sent
context.Request.Headers.Add("X-Client-Version", "1.4.0"); // headers and options
context.Request.SetBrowserRequestCredentials(BrowserRequestCredentials.Include); // cross-origin cookies in WebAssembly
try { return await next(context); } // call the server
catch (HttpRequestException e) when (e.StatusCode == HttpStatusCode.ServiceUnavailable)
{
return await next(context); // retrying is safe: each send builds a fresh request
}
}
}
builder.Services.AddScoped<IRemoteCallFilter, StampFilter>();
builder.Services.AddRemoteClients();
Use a DelegatingHandler for plain HTTP concerns. Use a filter when you need to know which
method is being called or want to work with the typed arguments and result.
Returning errors to the client
When a call fails, the proxy throws HttpRequestException with StatusCode set. If the response is
problem details (application/problem+json, RFC 9457), the message ends with its detail (or its
title), at most 1,000 characters:
Remote call MyApp.Client.IOrderService.SaveAsync failed: 409 Conflict. Order 42 was changed by someone else.
The endpoints send problem details for the errors they detect themselves: a body that isn't valid JSON, an unknown parameter, a missing or malformed query value. For your own errors, use ASP.NET Core's exception handling, which applies to the remote endpoints like any other:
builder.Services.AddProblemDetails();
builder.Services.AddExceptionHandler<BusinessErrorHandler>();
// ...
app.UseExceptionHandler();
sealed class BusinessErrorHandler(IProblemDetailsService problems) : IExceptionHandler
{
public async ValueTask<bool> TryHandleAsync(HttpContext context, Exception exception, CancellationToken ct)
{
if (exception is not ConcurrencyException) return false; // your own exception type
context.Response.StatusCode = StatusCodes.Status409Conflict;
return await problems.TryWriteAsync(new() { HttpContext = context, ProblemDetails = { Detail = exception.Message } });
}
}
Only map exceptions whose message is meant for users. An unhandled exception stays a 500, and in
production AddProblemDetails() doesn't put its message in the response.
Logging errors
There is no logging setting of its own: hook in whatever logger you already use (ILogger,
Serilog, Application Insights, Sentry) at the point you care about.
Client. A filter sees every failed call, with the method name and arguments:
public sealed class LogErrorsFilter(ILogger<LogErrorsFilter> log) : IRemoteCallFilter
{
public async Task<object?> InvokeAsync(RemoteCallContext context, RemoteCallDelegate next)
{
try { return await next(context); }
catch (Exception e) when (e is not OperationCanceledException)
{
// HttpRequestException.StatusCode and the problem details' detail (in the message) are on e
log.LogError(e, "Remote call {Interface}.{Method} failed", context.InterfaceName, context.MethodName);
throw;
}
}
}
builder.Services.AddScoped<IRemoteCallFilter, LogErrorsFilter>();
Register it first so it also sees errors thrown by later filters.
Server. The remote endpoints are ordinary minimal-API endpoints, so ASP.NET Core already logs
unhandled exceptions, and an IExceptionHandler (above) can log before it answers. To log only
the remote endpoints, add an endpoint filter to the group MapRemoteServices() returns:
app.MapRemoteServices().AddEndpointFilter(async (context, next) =>
{
try { return await next(context); }
catch (Exception e)
{
context.HttpContext.RequestServices.GetRequiredService<ILogger<Program>>()
.LogError(e, "Remote endpoint {Path} failed", context.HttpContext.Request.Path);
throw;
}
});
The library's own setup warnings (an interface missing from DI, a factory registration) are
logged under the category Blazor.AutoGen, so Logging:LogLevel:Blazor.AutoGen in
appsettings.json controls them.
Cookies and token refresh
- Cookies: in the browser, same-origin calls send the auth cookie automatically. For a
cross-origin API, set
SetBrowserRequestCredentials(Include)in a filter, as above. Outside the browser, give yourHttpClientaCookieContainer. - Token refresh: use the usual
DelegatingHandler: attach the token, and on a 401 refresh it once and resend. The generated request body can be sent again. Doing the same in a filter also works.
Both patterns are tested in CookieAndTokenTests, including 50 concurrent calls with an expired
token that trigger exactly one refresh.
Thread safety
One proxy is shared by everything in a scope, and in WebAssembly the whole app is one scope.
Everything per call is created per call: the context, the argument array, the pipeline and the
request message. JSON options are created once and are thread-safe once in use. Filters
registered as singleton or scoped are shared by concurrent calls, so keep per-call state in
context.Items rather than in fields.
ConcurrencyTests runs 500 parallel calls through one proxy, a shared filter that rewrites
arguments, 200 scopes starting at once, and concurrent requests from 20 different users. It
checks that no call sees another call's data.
JSON: System.Text.Json on the wire, Newtonsoft next to it
The wire format belongs to the generated code, not to your app: System.Text.Json with web
defaults on both sides. App-wide settings, such as ConfigureHttpJsonOptions or MVC controllers
using AddNewtonsoftJson(), don't affect the generated endpoints, so the two sides can't
silently disagree. To customize the wire format, pass the same method to both sides:
// In the .Client project (the server references it)
public static class WireJson
{
public static void Configure(JsonSerializerOptions o) => o.Converters.Add(new JsonStringEnumConverter());
}
builder.Services.AddRemoteClients(configureJson: WireJson.Configure); // .Client Program.cs
builder.Services.AddRemoteServices(WireJson.Configure); // server Program.cs
If only one side is configured, the call fails with a 400 rather than returning wrong data.
Using Newtonsoft and System.Text.Json together is fine (tested in JsonTests): an MVC API
using Newtonsoft and the generated endpoints can live in the same app, and share DTOs. The one
trap is a DTO that only Newtonsoft can read, such as one that relies on Newtonsoft's
[JsonProperty] on a private setter, renamed properties, or Newtonsoft's [JsonConstructor].
In-process calls never serialize, so it works during server rendering and breaks once
WebAssembly takes over. The generator warns about it (BAG010); the fix is to put the
System.Text.Json attribute next to the Newtonsoft one:
public class OrderDto
{
[Newtonsoft.Json.JsonProperty("full_name"), System.Text.Json.Serialization.JsonPropertyName("full_name")]
public string FullName { get; set; } = "";
}
JObject and JArray parameters or results are flagged too (BAG008).
Smaller responses: compression (opt-in)
Repeated property names make up much of a JSON list, and compression removes them almost entirely. Measured on a list of orders with 3 line items each:
| 1 order | 100 orders | |
|---|---|---|
| JSON as sent | 383 B | 37,761 B |
| gzip | 236 B | 6,654 B (82% smaller) |
| single-letter property names, no compression | 245 B | 23,961 B (37% smaller) |
| single-letter names + gzip | 177 B | 6,359 B (only 4% less than gzip alone) |
Turn it on in the server's Program.cs:
builder.Services.AddRemoteServices(compressResponses: true);
- Only the remote endpoints' responses are compressed, not the rest of your app.
- Responses of 1 KB or more are compressed with Brotli, or gzip when that's all the client
accepts (
Accept-Encoding, honoringq=0). Smaller ones are sent as they are, because compression has a fixed cost and can make a few bytes larger. Every response getsVary: Accept-Encoding, so caches keep the two versions apart. - A client that doesn't send
Accept-Encodinggets plain JSON, so nothing breaks. - If your app also uses
UseResponseCompression()or a compressing proxy, responses aren't compressed twice: those skip a response that already has aContent-Encoding.
Clients:
Blazor WebAssembly: nothing to do. The browser asks for compression and decompresses.
MAUI, WPF, WinForms and other .NET clients: .NET's
HttpClientdoesn't decompress by default, so it never asks for a compressed response. Turn it on in theHttpClientyou pass:builder.Services.AddRemoteClients(sp => new HttpClient( new HttpClientHandler { AutomaticDecompression = DecompressionMethods.All }) { BaseAddress = new Uri("https://api.example.com/") });
Risks:
- BREACH (HTTPS): an attacker who can put text into a response that also contains a secret, and can watch the compressed size of many requests, can guess the secret byte by byte. That's why ASP.NET Core's own response compression is off for HTTPS by default. A risky response combines a secret (a token, an API key, a session or CSRF value) with something an attacker controls, such as echoed search text or another user's comment. Order lists and catalogs are not risky.
- CPU: compression costs server CPU on every large response. Brotli runs at its fastest level here, which keeps that small, but measure on a busy server.
Recommendation:
- If a reverse proxy, CDN or load balancer in front of the app already compresses responses, use that and leave this off.
- Otherwise turn it on when remote calls return lists or other large results, especially for WebAssembly users on mobile connections.
- Leave it off, or give those methods their own non-compressed endpoint, if responses carry secrets next to user-controlled text (see BREACH above).
Other ways to make responses smaller:
- Leave out nulls: pass
configureJson: o => o.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNullto bothAddRemoteServicesandAddRemoteClients. - Short names where it matters:
[JsonPropertyName("n")]on a large DTO works on both sides today, and you choose the names, so they never change on their own. - Why there's no automatic single-letter naming: the names would have to come from property order. During a deploy, a browser can still run last week's WebAssembly app against the new server. If a DTO gained a property in the middle, the letters shift and a value silently lands in the wrong property, with no error. With real names, a mismatch just leaves a property empty. As the table shows, it would also save only about 4% once compression is on.
Registering services yourself
AddRemoteServices() uses TryAddScoped, so an interface you've already registered keeps your
registration. You can also skip AddRemoteServices() and register services yourself; the
endpoints resolve the interface from DI. MapRemoteServices() logs a warning at startup for each
[Remote] interface that nothing registered, since every call to it would fail with 500. Without
AddRemoteServices() it also logs one warning (since 0.1.0-preview.13): it can't tell which class you
registered, so [Authorize] on that class may not be read. Put such attributes on the interface
methods or the route group instead (see Authorization and the current user).
GET and DELETE endpoints always refuse cross-site requests that aren't CORS fetches in that case:
turning the check off takes AddRemoteServices(refuseCrossSiteRequests: false).
How it works
The generator runs in both projects and decides what to emit from what the project references:
| Project references | Generated (all internal) |
|---|---|
| ASP.NET Core (Blazor Web App server, Web API) | MapRemoteServices(), AddRemoteServices(), one handler per remote method at /_remote/{Namespace.IInterface}/{Method}, with the HTTP method its name or [Remote] gives |
Blazor WebAssembly / .Client project |
a proxy class per interface and AddRemoteClients(), defaulting to the app's base address |
| Blazor Hybrid (MAUI, WPF, WinForms) and other .NET clients with DI | the same proxies; AddRemoteClients(httpClient) requires the HttpClient factory, since there's no server address to default to |
| Plain class library (shared contracts) | nothing; the projects that reference it generate the code |
Any project with <BlazorAutoGenEnabled>false</BlazorAutoGenEnabled> |
nothing, but the BAG diagnostics still run |
Interfaces can live in the .Client project or in a shared class library that both projects
reference. Parameters are sent as one JSON object in the request body (for GET and DELETE, in the
query string), and the result comes back as JSON. CancellationToken parameters are passed through
and not sent.
Where the generated code lives (and why it isn't in git)
Only what you write is in your repository: the [Remote] interface and the server class. The
proxy, the endpoints and the registrations (Blazor.AutoGen.Client.g.cs and
Blazor.AutoGen.Server.g.cs) are never written to your project. A source generator runs inside
the C# compiler on every build and hands its output to the compiler in memory, so it's compiled
straight into your app's DLL.
That means there's nothing to keep in sync and nothing to commit: change the interface, and the next build (or the IDE, as you type) regenerates everything.
Seeing the generated code:
In the IDE: in Visual Studio, Solution Explorer → your project → Dependencies → Analyzers → Blazor.AutoGen.Generator → RemoteGenerator. In Rider, Dependencies → Source Generators. You can also press F12 on
AddRemoteClients()orMapRemoteServices(). The files are read-only.On disk, to read or diff it between versions:
dotnet build -p:EmitCompilerGeneratedFiles=trueThe files land under
obj/<Configuration>/<TargetFramework>/generated/Blazor.AutoGen.Generator/.obj/is build output, and the standard .NET.gitignorealready leaves it out.
Should you commit it? We recommend not to: the compiler regenerates it on every build, so a committed copy is only a stale duplicate. If your team wants it in git anyway, for example to see generated changes in code review, write it to a folder of its own and keep that folder out of the compilation, or the code is compiled twice and the build fails with duplicate definitions:
<PropertyGroup>
<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
<CompilerGeneratedFilesOutputPath>Generated</CompilerGeneratedFilesOutputPath>
</PropertyGroup>
<ItemGroup>
<Compile Remove="Generated/**" />
</ItemGroup>
Rules the generator checks
| Id | Severity | Rule |
|---|---|---|
| BAG001 | Error | A remote method returns Task, Task<T>, ValueTask or ValueTask<T> |
| BAG002 | Error | A remote method has no type parameters |
| BAG004 | Error | No ref, out or in parameters |
| BAG005 | Error | A remote interface is not generic |
| BAG006 | Error | A remote interface declares only methods |
| BAG007 | Error | A remote interface doesn't inherit other interfaces |
| BAG008 | Warning | Parameter and return types can be sent as JSON (not object, dynamic, tuples, stacks, Stream, IQueryable, JObject/JArray), and neither can the public properties of the DTOs they contain, at any depth. Stacks reverse order on every hop |
| BAG009 | Warning | One implementation per interface in the project, otherwise register it yourself |
| BAG010 | Warning | DTOs don't rely on Newtonsoft.Json attributes that have no System.Text.Json counterpart |
| BAG011 | Error | No two remote endpoints share a route and HTTP method (routes compared case-insensitively, as ASP.NET Core does), across projects too |
| BAG012 | Error | No remote endpoint has the same route as a controller action that accepts the same HTTP method, in the server project |
| BAG013 | Error | Routes are literal paths: no {parameters}, leftover [tokens], ?, #, ", \, spaces or empty segments |
| BAG014 | Info | Your controllers follow a route pattern and remote endpoints don't: suggests the exact RemoteConvention line |
| BAG015 | Warning | A DTO uses [JsonExtensionData] JsonObject, which System.Text.Json 10 writes as invalid JSON (fixed in .NET 11); use Dictionary<string, JsonElement> |
| BAG016 | Error | GET and DELETE parameters are simple values (strings, numbers, bool, char, enums, Guid, dates and times, nullable or in an array or list), since they travel in the query string |
| BAG017 | Info | A Get/Find/Delete... method stays POST because a parameter can't go in a query string, or is a collection that could make the URL too long (the name would have made it a GET or DELETE) |
| BAG018 | Error | The project's target framework has the .NET 8 APIs the generated code needs; otherwise no code is generated (set BlazorAutoGenEnabled to false to keep only the diagnostics) |
| BAG019 | Error (build) | The build uses the .NET 8 SDK / Visual Studio 17.8 or later, which can load the generator. Reported by the package's MSBuild targets, before compiling |
| BAG020 | Warning | No interface or abstract class without [JsonDerivedType] (or a [JsonConverter]) is sent, at any depth: System.Text.Json can write one but not read it back |
BAG003 ("no overloads") was retired: overloads now get their own routes.
Diagnostics point at your source, so #pragma warning disable BAG010 and .editorconfig
severity settings both work.
Limitations (v0.1)
- Data crosses the wire as JSON. Return DTOs, not EF entities with cycles. Apps that turn off
reflection-based
System.Text.Jsonaren't supported yet. - Interactive Auto fetches again after prerendering. Use .NET 10
[PersistentState]in the component, as in the sample. - On the server, a circuit keeps scoped services alive for its whole lifetime. Prefer
IDbContextFactory<T>over injecting aDbContextdirectly. - Routes are literal paths; route parameters such as
{id}aren't supported. GET and DELETE parameters travel in the query string instead, and must be simple values (BAG016). - Controller conflicts (BAG012) are checked for attribute-routed controllers in the server project. Conventionally routed controllers, minimal APIs you map yourself, and endpoints from other assemblies aren't checked; ASP.NET Core reports those collisions at request time.
- Not supported yet: streaming (
IAsyncEnumerable), file upload and download, and deriving the interface from a class.
Performance
Measured with benchmarks/ (BenchmarkDotNet,
.NET 10, Release, one developer machine). Use the numbers to compare against each other, not as
absolutes.
Generator (each interface has 10 methods, one type per file):
| Remote interfaces | Full build pass | Each IDE keystroke | Empty generator, same keystroke |
|---|---|---|---|
| 1 | 0.3 ms | 0.09 ms | 0.01 ms |
| 10 | 1.6 ms | 0.21 ms | 0.02 ms |
| 100 | 16 ms | 1.7 ms | 0.14 ms |
The generated code is fully cached between edits; only the model is rebuilt, and tests check that. In the sample app's real build, the generator takes 12 ms (client) and 47 ms (server), less than the Razor generator in the same projects.
In a large production app (a Blazor Web App server project of about 3,000 files with MVC controllers), the generator spends about 1.5 s of CPU in a full server compile of about 300 s. Most of that is Roslyn binding class declarations for the first time, which looking for implementations and controllers needs. Client projects and shared libraries skip that scan.
Per call (real Kestrel on loopback with a socket HttpClient, each benchmark in its own process):
| Mean | Allocated | |
|---|---|---|
Hand-written minimal API endpoint + HttpClient, int |
100.9 µs | 6.2 KB |
| Generated endpoint + proxy, int | 102.8 µs | 6.3 KB |
| Hand-written, record | 105.9 µs | 6.5 KB |
| Generated, record | 106.5 µs | 6.8 KB |
| Generated, int, with 2 filters | 104.2 µs | 7.8 KB |
| In-process call (server rendering) | 0.0005 µs | 0 |
Measured on 0.1.0-preview.10, hand-written and generated in the same run. Generated calls are within
1–2% of hand-written code in time and 2–4% in allocations. Without
filters they take a fast path that does the same work as hand-written code. The benchmarks also
run over the in-memory TestServer. Don't use those numbers to compare: some cases there take twice as long
because of thread scheduling inside TestServer, even though CPU profiles show the same work
(see the comments in RuntimeBenchmarks.cs).
Why the generated types are sealed classes, not structs. The proxy, the request classes,
RemoteHttp and the per-method descriptors are all sealed classes. Structs wouldn't make calls
faster:
JsonContent.Create<T>stores the request asobject, so a struct request would be boxed onto the heap anyway, which is the allocation a struct is meant to avoid.- Generic code such as
CallAsync<TRequest, TResult>is compiled once for all reference types but once per struct type, so struct requests would grow the WebAssembly download with every method. - The request object is about 30 bytes of the 6.3 KB a call allocates, and a call takes about 100 µs, mostly network and JSON. Removing it would change the result by well under 1%.
- The descriptors are created once and kept in
static readonlyfields; as structs they could be copied on every call.
sealed itself changes little here: components call the proxy through its interface, which is
dispatched the same way either way. What's left between generated and hand-written calls (1–2%) is
the work for filters and error handling, not how the types are declared.
dotnet run -c Release --project benchmarks/Blazor.AutoGen.Benchmarks -- --filter *
Add --inprocess for a quicker but noisier run.
Download size (what the browser downloads for the WebAssembly app). The sample's .Client
project (11 remote methods in 2 services, 4 pages) was published in Release three times: with the
generated proxies, and with Blazor.AutoGen removed and hand-written HttpClient clients making
the same calls, in two styles:
- Minimal: one-line methods that route every call through a few shared helpers. About the smallest client you'd write by hand.
- Typical: one
asyncmethod per call, each with its ownHttpRequestMessage, status check and error message, and a request DTO per body method. The style many teams write.
Every file in _framework was compared, then the same with 100 and 300 more methods added to all
three apps (a mix of get by id, search, create, update and delete). Generated minus hand-written:
| Remote methods | vs minimal (Brotli) | vs typical (Brotli) | vs minimal (uncompressed) | vs typical (uncompressed) |
|---|---|---|---|---|
| 11 | +7.5 KB (+0.25%) | +8.7 KB (+0.29%) | +13.3 KB (+0.13%) | +14.3 KB (+0.14%) |
| 111 | +11.2 KB (+0.37%) | −5.1 KB (−0.17%) | +43.5 KB (+0.43%) | −98.8 KB (−0.97%) |
| 311 | +19.0 KB (+0.63%) | −28.9 KB (−0.94%) | +113.1 KB (+1.13%) | −338.4 KB (−3.23%) |
Brotli is what servers send; uncompressed is what the browser holds after unpacking. Per method
after Brotli, the generated code costs about 58 bytes, the minimal style about 20 and the typical
style about 184: every async method compiles to its own state machine class. The generated code
has a fixed cost of about 8 KB (Blazor.AutoGen.wasm is 2.7 KB of it: the attributes and filter
types), so it's a little bigger than either style in a small app and smaller than the typical style
from about 80 methods on. The minimal style stays smaller, by about 38 bytes per method, but has
none of the filter pipeline, typed request classes or exact query formatting the generated proxy
carries.
How it got smaller:
- 0.1.0-preview.8 (11 methods: 11.7 KB → 7.1 KB): the package targets
net8.0as well asnetstandard2.0, so .NET 8+ apps no longer download thenetstandard.wasmfacade; the library is marked trimmable; and the proxies share one helper for the filter path instead of anasyncmethod each, since everyasyncmethod compiles to a separate state machine class. - 0.1.0-preview.10 (311 methods: 28.1 KB → 17.9 KB, 250 KB → 110 KB uncompressed): each method
gets one descriptor holding its route, HTTP method, names and filter builder, instead of three
fields, a cached lambda and ten arguments at every call; proxy methods are plain public methods,
so their stored names aren't
Namespace.IInterface.Method; error messages are put together only when a call fails, instead of storing a label per method; and request classes use fields instead of auto-properties.
Measure it yourself, for example after changing the emitters:
pwsh benchmarks/Size/measure.ps1 # the sample's 11 methods, all three variants
pwsh benchmarks/Size/measure.ps1 -ExtraMethods 300 # plus 300 more
Sample
samples/SampleApp is the stock dotnet new blazor -int Auto -au Individual
template, with the Weather page moved to the .Client project and backed by IWeatherService, and a
Products page backed by IProductService that covers every scenario in this README:
| Scenario | Where |
|---|---|
| HTTP methods from method names (the default) | Weather's Get... methods are GETs; SampleApp.Client/Services/RemoteSetup.cs shows how to turn it off |
| GET with query parameters, including an enum array and an optional string | Products: Search, Details |
| POST with a DTO body (explicit, since a DTO can't go in a query string) | Products: Up to 10.00 |
POST, PUT, PATCH (explicit Method, custom route) and DELETE |
Products: Add, +1 stock, Set, Delete |
[Authorize] on a DELETE endpoint |
Products: Delete while signed out answers 401 |
Response compression (compressResponses: true) |
SampleApp/Program.cs; Products: Load all comes back Brotli-compressed |
An IRemoteCallFilter |
SampleApp.Client/Services/CallLog.cs logs each call's HTTP method on the Products page |
dotnet run --project samples/SampleApp --launch-profile http
Open /weather or /products. Each page shows whether it's rendered by Server or WebAssembly
(the first visit uses Server while WebAssembly downloads, so reload once). Use the buttons and watch
the browser's network tab, or the call log at the bottom of the Products page.
Requirements
- Tested on .NET 10. The generated code only uses APIs from .NET 8 onwards, but .NET 8 and 9 are not covered by CI yet.
- Projects that generate code (the server and the
.Clientproject) must target .NET 8 or later; anything older gets BAG018 instead of code. - The package has a
net8.0build, which .NET 8, 9 and 10 apps use, and anetstandard2.0build, so a contracts library for older targets can declare[Remote]interfaces. If such a library also references DI andSystem.Net.Http.Json, set<BlazorAutoGenEnabled>false</BlazorAutoGenEnabled>in it. - The generator needs Roslyn 4.8: the .NET 8 SDK or Visual Studio 17.8 and later. Older tooling
gets BAG019 instead of a missing
AddRemoteServices().
Contributing
Issues and pull requests are welcome. See CONTRIBUTING.md.
License
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net5.0 was computed. net5.0-windows was computed. net6.0 was computed. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 was computed. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
| .NET Core | netcoreapp2.0 was computed. netcoreapp2.1 was computed. netcoreapp2.2 was computed. netcoreapp3.0 was computed. netcoreapp3.1 was computed. |
| .NET Standard | netstandard2.0 is compatible. netstandard2.1 was computed. |
| .NET Framework | net461 was computed. net462 was computed. net463 was computed. net47 was computed. net471 was computed. net472 was computed. net48 was computed. net481 was computed. |
| MonoAndroid | monoandroid was computed. |
| MonoMac | monomac was computed. |
| MonoTouch | monotouch was computed. |
| Tizen | tizen40 was computed. tizen60 was computed. |
| Xamarin.iOS | xamarinios was computed. |
| Xamarin.Mac | xamarinmac was computed. |
| Xamarin.TVOS | xamarintvos was computed. |
| Xamarin.WatchOS | xamarinwatchos was computed. |
-
.NETStandard 2.0
- No dependencies.
-
net8.0
- No dependencies.
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 0.1.0-preview.13 | 0 | 11/30/2026 |
| 0.1.0-preview.12 | 0 | 11/30/2026 |
| 0.1.0-preview.11 | 39 | 11/30/2026 |
| 0.1.0-preview.10 | 42 | 11/30/2026 |
| 0.1.0-preview.9 | 47 | 11/30/2026 |
| 0.1.0-preview.8 | 40 | 11/30/2026 |
| 0.1.0-preview.7 | 43 | 11/30/2026 |
| 0.1.0-preview.6 | 41 | 11/30/2026 |
| 0.1.0-preview.5 | 47 | 11/29/2026 |
| 0.1.0-preview.4 | 47 | 11/29/2026 |
| 0.1.0-preview.3 | 42 | 11/29/2026 |
| 0.1.0-preview.2 | 46 | 11/29/2026 |