GCR deployment testing in progress - content type issue still remaining.

This commit is contained in:
2026-05-05 14:42:03 +05:00
parent 40fe69ed65
commit f8112f897e
22 changed files with 348 additions and 2431 deletions
+6 -1
View File
@@ -1,13 +1,18 @@
using System.Text.Json.Serialization;
using Htmx.ApiDemo.Templates;
using Microsoft.AspNetCore.Http;
namespace Htmx.ApiDemo;
[JsonSerializable(typeof(string))]
[JsonSerializable(typeof(Task), GenerationMode = JsonSourceGenerationMode.Metadata)]
[JsonSerializable(typeof(ValueTask), GenerationMode = JsonSourceGenerationMode.Metadata)]
[JsonSerializable(typeof(IResult), GenerationMode = JsonSourceGenerationMode.Metadata)]
[JsonSerializable(typeof(Task<IResult>), GenerationMode = JsonSourceGenerationMode.Metadata)]
[JsonSerializable(typeof(ValueTask<IResult>), GenerationMode = JsonSourceGenerationMode.Metadata)]
[JsonSerializable(typeof(PostLoginHandler.Command), TypeInfoPropertyName = "LoginCommand")]
[JsonSerializable(typeof(PostRegisterHandler.Command), TypeInfoPropertyName = "RegisterCommand")]
[JsonSerializable(typeof(PostLogoutHandler.Command), TypeInfoPropertyName = "LogoutCommand")]
internal partial class AppJsonSerializerContext : JsonSerializerContext
{
}
+11
View File
@@ -13,8 +13,19 @@
<EnableRequestDelegateGenerator>true</EnableRequestDelegateGenerator>
<PublishAot>true</PublishAot>
<InterceptorsPreviewNamespaces>$(InterceptorsPreviewNamespaces);Immediate.Apis.Generators</InterceptorsPreviewNamespaces>
<!--
IL2026 warnings come from STJ-generated serializers for Task → AggregateException → Exception.TargetSite.
We register Task/ValueTask in AppJsonSerializerContext only so RequestDelegateFactory.GetTypeInfo()
doesn't throw at startup — we never actually serialize a Task. TargetSite is unsupported in
NativeAOT anyway, so suppressing this warning here is safe.
-->
<NoWarn>$(NoWarn);IL2026</NoWarn>
</PropertyGroup>
<ItemGroup>
<RdXmlFile Include="rd.xml" />
</ItemGroup>
<ItemGroup>
<CompilerVisibleProperty Include="RootNamespace" />
<CompilerVisibleProperty Include="MSBuildProjectDirectory" />
+3 -7
View File
@@ -12,7 +12,7 @@ namespace Htmx.ApiDemo;
/// </summary>
public static class HtmxPageExtensions
{
public static void WriteHtmxPage(
public static HtmxResult WriteHtmxPage(
this HttpContext ctx,
IHtmxComponent body,
string title = "App",
@@ -21,24 +21,20 @@ public static class HtmxPageExtensions
{
if (ctx.Request.Headers.ContainsKey("HX-Request"))
{
// Partial swap: tell HTMX to update the browser <title> tag
ctx.Response.Headers["HX-Title"] = title;
ctx.WriteHtmxBody(body);
return ctx.WriteHtmxBody(body);
}
else
{
// Resolve display name: prefer DisplayName claim, fall back to email/name
string? userName = ctx.User.Identity?.IsAuthenticated == true
? (ctx.User.FindFirst("DisplayName")?.Value
?? ctx.User.FindFirst(System.Security.Claims.ClaimTypes.Name)?.Value)
: null;
// Resolve antiforgery token for the logout form in the layout
var antiforgery = ctx.RequestServices.GetRequiredService<IAntiforgery>();
var afTokens = antiforgery.GetAndStoreTokens(ctx);
// Full page load: wrap in the shell layout
ctx.WriteHtmxBody(new Templates.MainLayout(body, title, appName, pageTitle, userName, afTokens.RequestToken));
return ctx.WriteHtmxBody(new Templates.MainLayout(body, title, appName, pageTitle, userName, afTokens.RequestToken));
}
}
}
+31
View File
@@ -0,0 +1,31 @@
using Microsoft.AspNetCore.Http;
namespace Htmx.ApiDemo;
/// <summary>
/// IResult implementation for rendering Htmx components as HTML or issuing redirects.
/// Defined as user code (not source-generated) so that RequestDelegateGenerator can
/// see it and emit NativeAOT-safe endpoint interceptors for lambdas returning this type.
/// </summary>
public readonly struct HtmxResult : IResult
{
private readonly IHtmxComponent? _component;
private readonly string? _redirectUrl;
public HtmxResult(IHtmxComponent component) { _component = component; _redirectUrl = null; }
public HtmxResult(string redirectUrl) { _component = null; _redirectUrl = redirectUrl; }
public Task ExecuteAsync(HttpContext context)
{
if (_redirectUrl is not null)
{
context.Response.Redirect(_redirectUrl);
return Task.CompletedTask;
}
context.Response.ContentType = "text/html; charset=utf-8";
var writerContext = new HtmxRenderContext(context.Response.BodyWriter);
_component!.Render(writerContext);
return Task.CompletedTask;
}
}
+49 -1
View File
@@ -9,9 +9,16 @@ using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Serializers;
using MongoDB.Driver;
// ── Explicit serializer registrations — force AOT to preserve constructors ─
BsonSerializer.RegisterSerializer(new ObjectIdSerializer());
BsonSerializer.RegisterSerializer(new StringSerializer());
BsonSerializer.RegisterSerializer(new DateTimeSerializer());
BsonSerializer.RegisterSerializer(new BooleanSerializer());
BsonSerializer.RegisterSerializer(new NullableSerializer<DateTime>(new DateTimeSerializer()));
// ── Explicit BsonClassMap — no AutoMap() reflection, fully AOT-safe ───────
BsonClassMap.RegisterClassMap<AppUser>(cm =>
{
cm.AutoMap();
cm.MapIdProperty(u => u.Id).SetSerializer(new ObjectIdSerializer());
cm.MapProperty(u => u.Email).SetElementName("email");
cm.MapProperty(u => u.NormalizedEmail).SetElementName("normalizedEmail");
@@ -95,6 +102,47 @@ app.Use(async (context, next) =>
await next();
});
app.MapHtmxApiDemoEndpoints();
// Explicit MapGet/MapPost so RequestDelegateGenerator can intercept and emit
// NativeAOT-safe endpoint code. Handlers return ValueTask<IResult> which the
// generator knows how to handle: it emits `await result.ExecuteAsync(httpContext)`.
app.MapGet("/", static (
[AsParameters] Htmx.ApiDemo.Templates.GetIndexHandler.Command cmd,
Htmx.ApiDemo.Templates.GetIndexHandler.Handler handler,
CancellationToken token) => handler.HandleAsync(cmd, token));
app.MapGet("/greet/{username}/{count?}/{id?}", static (
[AsParameters] Htmx.ApiDemo.Templates.GetGreetingHandler.Query query,
Htmx.ApiDemo.Templates.GetGreetingHandler.Handler handler,
CancellationToken token) => handler.HandleAsync(query, token));
app.MapGet("/login", static (
[AsParameters] Htmx.ApiDemo.Templates.GetLoginHandler.Query query,
Htmx.ApiDemo.Templates.GetLoginHandler.Handler handler,
CancellationToken token) => handler.HandleAsync(query, token));
app.MapPost("/login", static (
[AsParameters] Htmx.ApiDemo.Templates.PostLoginHandler.Command cmd,
Htmx.ApiDemo.Templates.PostLoginHandler.Handler handler,
CancellationToken token) => handler.HandleAsync(cmd, token));
app.MapGet("/register", static (
[AsParameters] Htmx.ApiDemo.Templates.GetRegisterHandler.Query query,
Htmx.ApiDemo.Templates.GetRegisterHandler.Handler handler,
CancellationToken token) => handler.HandleAsync(query, token));
app.MapPost("/register", static (
[AsParameters] Htmx.ApiDemo.Templates.PostRegisterHandler.Command cmd,
Htmx.ApiDemo.Templates.PostRegisterHandler.Handler handler,
CancellationToken token) => handler.HandleAsync(cmd, token));
app.MapPost("/logout", static (
[AsParameters] Htmx.ApiDemo.Templates.PostLogoutHandler.Command cmd,
Htmx.ApiDemo.Templates.PostLogoutHandler.Handler handler,
CancellationToken token) => handler.HandleAsync(cmd, token));
app.MapGet("/ui-demo", static (
[AsParameters] Htmx.ApiDemo.Templates.GetUiDemoHandler.Query query,
Htmx.ApiDemo.Templates.GetUiDemoHandler.Handler handler,
CancellationToken token) => handler.HandleAsync(query, token));
app.Run();
+13 -5
View File
@@ -1,5 +1,7 @@
using Immediate.Apis.Shared;
using Immediate.Handlers.Shared;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace Htmx.ApiDemo.Templates;
@@ -21,9 +23,14 @@ public sealed class Greeting : GreetingBase
[MapGet("/greet/{username}/{count?}/{id?}")]
public static partial class GetGreetingHandler
{
public record Query(string Username, int? Count, Guid? Id);
public class Query
{
[FromRoute] public string Username { get; set; } = default!;
[FromRoute] public string? Count { get; set; }
[FromRoute] public string? Id { get; set; }
}
private static ValueTask HandleAsync(
private static ValueTask<IResult> HandleAsync(
Query query,
IHttpContextAccessor httpContextAccessor,
CancellationToken token)
@@ -31,8 +38,9 @@ public static partial class GetGreetingHandler
var context = httpContextAccessor.HttpContext
?? throw new InvalidOperationException("HttpContext is not available.");
var template = new Greeting { Username = query.Username, Count = query.Count + 1 ?? 0, GreetingId = query.Id ?? Guid.NewGuid() };
context.WriteHtmxBody(template);
return ValueTask.CompletedTask;
var count = int.TryParse(query.Count, out var parsedCount) ? parsedCount + 1 : 0;
var greetingId = Guid.TryParse(query.Id, out var parsedId) ? parsedId : Guid.NewGuid();
var template = new Greeting { Username = query.Username, Count = count, GreetingId = greetingId };
return ValueTask.FromResult<IResult>(context.WriteHtmxBody(template));
}
}
+13 -18
View File
@@ -2,6 +2,7 @@ using Htmx.ApiDemo.Data;
using Immediate.Apis.Shared;
using Immediate.Handlers.Shared;
using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace Htmx.ApiDemo.Templates;
@@ -31,9 +32,9 @@ public sealed class Login : LoginBase
[MapGet("/login")]
public static partial class GetLoginHandler
{
public record Query;
public class Query;
private static ValueTask HandleAsync(
private static ValueTask<IResult> HandleAsync(
Query _,
IHttpContextAccessor httpContextAccessor,
IAntiforgery antiforgery,
@@ -43,14 +44,10 @@ public static partial class GetLoginHandler
?? throw new InvalidOperationException("HttpContext is not available.");
if (ctx.User.Identity?.IsAuthenticated == true)
{
ctx.Response.Redirect("/");
return ValueTask.CompletedTask;
}
return ValueTask.FromResult<IResult>(new HtmxResult("/"));
var afTokens = antiforgery.GetAndStoreTokens(ctx);
ctx.WriteHtmxPage(new Login(afToken: afTokens.RequestToken), title: "Sign in", appName: "HtmxApp", pageTitle: "Sign in");
return ValueTask.CompletedTask;
return ValueTask.FromResult<IResult>(ctx.WriteHtmxPage(new Login(afToken: afTokens.RequestToken), title: "Sign in", appName: "HtmxApp", pageTitle: "Sign in"));
}
}
@@ -59,12 +56,13 @@ public static partial class GetLoginHandler
[MapPost("/login")]
public static partial class PostLoginHandler
{
public record Command(
[property: FromForm] string Email,
[property: FromForm] string Password
);
public class Command
{
[FromForm] public string Email { get; set; } = default!;
[FromForm] public string Password { get; set; } = default!;
}
private static async ValueTask HandleAsync(
private static async ValueTask<IResult> HandleAsync(
[AsParameters] Command command,
IHttpContextAccessor httpContextAccessor,
IAntiforgery antiforgery,
@@ -77,12 +75,9 @@ public static partial class PostLoginHandler
var (success, error) = await authService.LoginAsync(command.Email, command.Password);
if (success)
{
ctx.Response.Redirect("/");
return;
}
return new HtmxResult("/");
var afTokens = antiforgery.GetAndStoreTokens(ctx);
ctx.WriteHtmxPage(new Login(error, afToken: afTokens.RequestToken), title: "Sign in", appName: "HtmxApp", pageTitle: "Sign in");
return ctx.WriteHtmxPage(new Login(error, afToken: afTokens.RequestToken), title: "Sign in", appName: "HtmxApp", pageTitle: "Sign in");
}
}
+1 -1
View File
@@ -11,7 +11,7 @@ public static partial class PostLogoutHandler
{
// Empty command — [AsParameters] ensures form content-type is accepted
// and antiforgery token in the form is validated by the middleware.
public record Command;
public class Command;
private static async ValueTask HandleAsync(
[AsParameters] Command _,
+4 -5
View File
@@ -2,6 +2,7 @@ using Htmx.ApiDemo;
using Htmx.ApiDemo.Templates.Components;
using Immediate.Apis.Shared;
using Immediate.Handlers.Shared;
using Microsoft.AspNetCore.Http;
namespace Htmx.ApiDemo.Templates;
@@ -73,9 +74,9 @@ public sealed class MainLayout : MainLayoutBase
[MapGet("/")]
public static partial class GetIndexHandler
{
public record Command;
public class Command;
private static ValueTask HandleAsync(
private static ValueTask<IResult> HandleAsync(
Command command,
IHttpContextAccessor httpContextAccessor,
CancellationToken token)
@@ -84,8 +85,6 @@ public static partial class GetIndexHandler
?? throw new InvalidOperationException("HttpContext is not available.");
var greet = new Greeting { Username = "Enciphered", Count = 0, GreetingId = Guid.NewGuid() };
context.WriteHtmxPage(greet, title: "Home", appName: "HtmxApp", pageTitle: "Home");
return ValueTask.CompletedTask;
return ValueTask.FromResult<IResult>(context.WriteHtmxPage(greet, title: "Home", appName: "HtmxApp", pageTitle: "Home"));
}
}
+16 -22
View File
@@ -2,6 +2,7 @@ using Htmx.ApiDemo.Data;
using Immediate.Apis.Shared;
using Immediate.Handlers.Shared;
using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace Htmx.ApiDemo.Templates;
@@ -31,9 +32,9 @@ public sealed class Register : RegisterBase
[MapGet("/register")]
public static partial class GetRegisterHandler
{
public record Query;
public class Query;
private static ValueTask HandleAsync(
private static ValueTask<IResult> HandleAsync(
Query _,
IHttpContextAccessor httpContextAccessor,
IAntiforgery antiforgery,
@@ -43,14 +44,10 @@ public static partial class GetRegisterHandler
?? throw new InvalidOperationException("HttpContext is not available.");
if (ctx.User.Identity?.IsAuthenticated == true)
{
ctx.Response.Redirect("/");
return ValueTask.CompletedTask;
}
return ValueTask.FromResult<IResult>(new HtmxResult("/"));
var afTokens = antiforgery.GetAndStoreTokens(ctx);
ctx.WriteHtmxPage(new Register(afToken: afTokens.RequestToken), title: "Register", appName: "HtmxApp", pageTitle: "Create account");
return ValueTask.CompletedTask;
return ValueTask.FromResult<IResult>(ctx.WriteHtmxPage(new Register(afToken: afTokens.RequestToken), title: "Register", appName: "HtmxApp", pageTitle: "Create account"));
}
}
@@ -59,14 +56,15 @@ public static partial class GetRegisterHandler
[MapPost("/register")]
public static partial class PostRegisterHandler
{
public record Command(
[property: FromForm] string Email,
[property: FromForm] string Password,
[property: FromForm] string ConfirmPassword,
[property: FromForm] string? DisplayName
);
public class Command
{
[FromForm] public string Email { get; set; } = default!;
[FromForm] public string Password { get; set; } = default!;
[FromForm] public string ConfirmPassword { get; set; } = default!;
[FromForm] public string? DisplayName { get; set; }
}
private static async ValueTask HandleAsync(
private static async ValueTask<IResult> HandleAsync(
[AsParameters] Command command,
IHttpContextAccessor httpContextAccessor,
IAntiforgery antiforgery,
@@ -79,21 +77,17 @@ public static partial class PostRegisterHandler
if (command.Password != command.ConfirmPassword)
{
var afTokens1 = antiforgery.GetAndStoreTokens(ctx);
ctx.WriteHtmxPage(new Register("Passwords do not match.", afToken: afTokens1.RequestToken),
return ctx.WriteHtmxPage(new Register("Passwords do not match.", afToken: afTokens1.RequestToken),
title: "Register", appName: "HtmxApp", pageTitle: "Create account");
return;
}
var (success, error) = await authService.RegisterAsync(command.Email, command.Password, command.DisplayName);
if (success)
{
ctx.Response.Redirect("/");
return;
}
return new HtmxResult("/");
var afTokens2 = antiforgery.GetAndStoreTokens(ctx);
ctx.WriteHtmxPage(new Register(error, afToken: afTokens2.RequestToken),
return ctx.WriteHtmxPage(new Register(error, afToken: afTokens2.RequestToken),
title: "Register", appName: "HtmxApp", pageTitle: "Create account");
}
}
+4 -5
View File
@@ -1,6 +1,7 @@
using Htmx.ApiDemo.Templates.Components;
using Immediate.Apis.Shared;
using Immediate.Handlers.Shared;
using Microsoft.AspNetCore.Http;
namespace Htmx.ApiDemo.Templates;
@@ -370,9 +371,9 @@ public sealed class UiDemo : UiDemoBase
[MapGet("/ui-demo")]
public static partial class GetUiDemoHandler
{
public record Query;
public class Query;
private static ValueTask HandleAsync(
private static ValueTask<IResult> HandleAsync(
Query query,
IHttpContextAccessor httpContextAccessor,
CancellationToken token)
@@ -381,8 +382,6 @@ public static partial class GetUiDemoHandler
?? throw new InvalidOperationException("HttpContext is not available.");
var page = new UiDemo();
context.WriteHtmxPage(page, title: "UI Demo", appName: "HtmxApp", pageTitle: "UI Components");
return ValueTask.CompletedTask;
return ValueTask.FromResult<IResult>(context.WriteHtmxPage(page, title: "UI Demo", appName: "HtmxApp", pageTitle: "UI Components"));
}
}
+17
View File
@@ -0,0 +1,17 @@
<Directives xmlns="http://schemas.microsoft.com/netfx/2013/01/metadata">
<!--
NativeAOT runtime directives.
1. MongoDB.Bson: preserve all serializer constructors used via reflection.
2. Htmx.ApiDemo: preserve constructors of Query/Command types so that
the runtime RequestDelegateFactory can bind [AsParameters] parameters.
3. Microsoft.Extensions.Primitives: preserve StringValues coercion operators
used by RequestDelegateFactory expression trees (StringValues → string).
4. System.Private.CoreLib primitive types: preserve TryParse methods used
by RequestDelegateFactory to bind route/query values.
-->
<Application>
<Assembly Name="MongoDB.Bson" Dynamic="Required All" />
<Assembly Name="Htmx.ApiDemo" Dynamic="Required All" />
<Assembly Name="Microsoft.Extensions.Primitives" Dynamic="Required All" />
</Application>
</Directives>
File diff suppressed because one or more lines are too long