Removed Immediate.Apis, Added AOT Testing Scripts.
This commit is contained in:
@@ -5,14 +5,6 @@ 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
|
||||
{
|
||||
}
|
||||
@@ -10,7 +10,7 @@ namespace Htmx.ApiDemo.Data;
|
||||
/// No EF Core, no LINQ-to-SQL, no RelationalModel fully NativeAOT safe.
|
||||
/// IPasswordHasher is pure PBKDF2 crypto with no dynamic IL.
|
||||
/// </summary>
|
||||
public sealed class AuthService(
|
||||
public sealed class AppAuthService(
|
||||
MongoDbService mongo,
|
||||
IPasswordHasher<AppUser> passwordHasher,
|
||||
IHttpContextAccessor httpContextAccessor)
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
namespace Htmx.ApiDemo;
|
||||
|
||||
public static class HtmxExtensions
|
||||
{
|
||||
public static void HtmxAwareWriteToBody(
|
||||
this IHtmxComponent component, HttpContext context, string title, string appName, string pageTitle)
|
||||
{
|
||||
// If not a HX-Request, render the component inside main layout
|
||||
if (!context.Request.Headers.ContainsKey("HX-Request"))
|
||||
{
|
||||
var layout = new MainLayout(component, title: title, appName: appName, pageTitle: pageTitle,
|
||||
userName: context.User.Identity?.IsAuthenticated == true ? context.User.Identity.Name : null);
|
||||
|
||||
context.Response.ContentType = "text/html; charset=utf-8";
|
||||
var renderContext = new HtmxRenderContext(context.Response.BodyWriter);
|
||||
layout.Render(renderContext);
|
||||
return;
|
||||
}
|
||||
|
||||
//Else only render the component
|
||||
component.WriteToResponseBody(context);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
using Htmx.ApiDemo.Data;
|
||||
|
||||
namespace Htmx.ApiDemo;
|
||||
|
||||
public static partial class RouteMap
|
||||
{
|
||||
public static void MapHtmxRoutes(this WebApplication app)
|
||||
{
|
||||
MapGetIndex(app);
|
||||
GetRegister(app);
|
||||
PostRegister(app);
|
||||
PostLogout(app);
|
||||
GetLogin(app);
|
||||
PostLogin(app);
|
||||
GetUiDemo(app);
|
||||
}
|
||||
|
||||
private static void PostLogout(WebApplication app)
|
||||
=> app.MapPost("/logout", async (HttpContext context, AppAuthService authService) =>
|
||||
{
|
||||
await authService.SignOutAsync();
|
||||
return Results.Redirect("/login");
|
||||
});
|
||||
}
|
||||
@@ -10,20 +10,13 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
<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" />
|
||||
<TrimmerRootAssembly Include="MongoDB.Bson" />
|
||||
<TrimmerRootAssembly Include="Htmx.ApiDemo" />
|
||||
<TrimmerRootAssembly Include="Microsoft.Extensions.Primitives" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
@@ -38,8 +31,6 @@
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Immediate.Apis" Version="4.2.0" />
|
||||
<PackageReference Include="Immediate.Handlers" Version="3.5.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.7" />
|
||||
<PackageReference Include="MongoDB.Driver" Version="3.4.0" />
|
||||
<ProjectReference Include="..\Htmx.SourceGenerator\Htmx.SourceGenerator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
@Htmx.ApiDemo_HostAddress = http://localhost:5120
|
||||
|
||||
GET {{Htmx.ApiDemo_HostAddress}}/todos/
|
||||
Accept: application/json
|
||||
|
||||
###
|
||||
|
||||
GET {{Htmx.ApiDemo_HostAddress}}/todos/1
|
||||
Accept: application/json
|
||||
|
||||
###
|
||||
@@ -0,0 +1,24 @@
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 17
|
||||
VisualStudioVersion = 17.5.2.0
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Htmx.ApiDemo", "Htmx.ApiDemo.csproj", "{38A5EDEF-D21B-8D4E-D1F2-DDFE0335BD22}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Release|Any CPU = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{38A5EDEF-D21B-8D4E-D1F2-DDFE0335BD22}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{38A5EDEF-D21B-8D4E-D1F2-DDFE0335BD22}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{38A5EDEF-D21B-8D4E-D1F2-DDFE0335BD22}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{38A5EDEF-D21B-8D4E-D1F2-DDFE0335BD22}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {61C4ACCC-FDDE-4F92-B2A9-A5744496122B}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
@@ -1,40 +0,0 @@
|
||||
using Microsoft.AspNetCore.Antiforgery;
|
||||
|
||||
namespace Htmx.ApiDemo;
|
||||
|
||||
/// <summary>
|
||||
/// Renders a full page or just the body component depending on whether
|
||||
/// the request was made by HTMX (HX-Request header present).
|
||||
///
|
||||
/// Full request → wraps body in MainLayout (complete HTML page)
|
||||
/// HTMX request → renders body only + sets HX-Title so the browser
|
||||
/// tab title still updates
|
||||
/// </summary>
|
||||
public static class HtmxPageExtensions
|
||||
{
|
||||
public static HtmxResult WriteHtmxPage(
|
||||
this HttpContext ctx,
|
||||
IHtmxComponent body,
|
||||
string title = "App",
|
||||
string appName = "HtmxApp",
|
||||
string pageTitle = "")
|
||||
{
|
||||
if (ctx.Request.Headers.ContainsKey("HX-Request"))
|
||||
{
|
||||
ctx.Response.Headers["HX-Title"] = title;
|
||||
return ctx.WriteHtmxBody(body);
|
||||
}
|
||||
else
|
||||
{
|
||||
string? userName = ctx.User.Identity?.IsAuthenticated == true
|
||||
? (ctx.User.FindFirst("DisplayName")?.Value
|
||||
?? ctx.User.FindFirst(System.Security.Claims.ClaimTypes.Name)?.Value)
|
||||
: null;
|
||||
|
||||
var antiforgery = ctx.RequestServices.GetRequiredService<IAntiforgery>();
|
||||
var afTokens = antiforgery.GetAndStoreTokens(ctx);
|
||||
|
||||
return ctx.WriteHtmxBody(new Templates.MainLayout(body, title, appName, pageTitle, userName, afTokens.RequestToken));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
+5
-67
@@ -1,9 +1,11 @@
|
||||
using Htmx.ApiDemo;
|
||||
using Htmx.ApiDemo.Data;
|
||||
using Immediate.Handlers;
|
||||
using Htmx.ApiDemo.Templates;
|
||||
using Microsoft.AspNetCore.Antiforgery;
|
||||
using Microsoft.AspNetCore.Authentication.Cookies;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using MongoDB.Bson;
|
||||
using MongoDB.Bson.Serialization;
|
||||
using MongoDB.Bson.Serialization.Serializers;
|
||||
@@ -59,13 +61,10 @@ builder.Services
|
||||
});
|
||||
|
||||
builder.Services.AddScoped<IPasswordHasher<AppUser>, PasswordHasher<AppUser>>();
|
||||
builder.Services.AddScoped<AuthService>();
|
||||
builder.Services.AddScoped<AppAuthService>();
|
||||
|
||||
// ── App services ──────────────────────────────────────────────────────────
|
||||
builder.Services.AddHttpContextAccessor();
|
||||
builder.Services
|
||||
.AddHtmxApiDemoBehaviors()
|
||||
.AddHtmxApiDemoHandlers();
|
||||
builder.Services.AddOpenApi();
|
||||
builder.Services.AddAuthorization();
|
||||
|
||||
@@ -83,67 +82,6 @@ app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
app.UseAntiforgery();
|
||||
|
||||
// ── Guard: redirect unauthenticated users to /login ───────────────────────
|
||||
app.Use(async (context, next) =>
|
||||
{
|
||||
var path = context.Request.Path.Value ?? "";
|
||||
bool isPublic = path.StartsWith("/login", StringComparison.OrdinalIgnoreCase)
|
||||
|| path.StartsWith("/register", StringComparison.OrdinalIgnoreCase)
|
||||
|| path.StartsWith("/logout", StringComparison.OrdinalIgnoreCase)
|
||||
|| path.StartsWith("/css/", StringComparison.OrdinalIgnoreCase)
|
||||
|| path.StartsWith("/js/", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
if (!isPublic && context.User.Identity?.IsAuthenticated != true)
|
||||
{
|
||||
context.Response.Redirect("/login");
|
||||
return;
|
||||
}
|
||||
|
||||
await next();
|
||||
});
|
||||
|
||||
// Explicit MapGet/MapPost with explicit lambda return type ValueTask<IResult>.
|
||||
// The explicit return type annotation lets RequestDelegateGenerator see IResult
|
||||
// directly (without needing to resolve the generated Handler.HandleAsync type),
|
||||
// so it emits `await result.ExecuteAsync(httpContext)` instead of JSON serialization.
|
||||
app.MapGet("/", static ValueTask<IResult> (
|
||||
[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 ValueTask<IResult> (
|
||||
[AsParameters] Htmx.ApiDemo.Templates.GetGreetingHandler.Query query,
|
||||
Htmx.ApiDemo.Templates.GetGreetingHandler.Handler handler,
|
||||
CancellationToken token) => handler.HandleAsync(query, token));
|
||||
|
||||
app.MapGet("/login", static ValueTask<IResult> (
|
||||
[AsParameters] Htmx.ApiDemo.Templates.GetLoginHandler.Query query,
|
||||
Htmx.ApiDemo.Templates.GetLoginHandler.Handler handler,
|
||||
CancellationToken token) => handler.HandleAsync(query, token));
|
||||
|
||||
app.MapPost("/login", static ValueTask<IResult> (
|
||||
[AsParameters] Htmx.ApiDemo.Templates.PostLoginHandler.Command cmd,
|
||||
Htmx.ApiDemo.Templates.PostLoginHandler.Handler handler,
|
||||
CancellationToken token) => handler.HandleAsync(cmd, token));
|
||||
|
||||
app.MapGet("/register", static ValueTask<IResult> (
|
||||
[AsParameters] Htmx.ApiDemo.Templates.GetRegisterHandler.Query query,
|
||||
Htmx.ApiDemo.Templates.GetRegisterHandler.Handler handler,
|
||||
CancellationToken token) => handler.HandleAsync(query, token));
|
||||
|
||||
app.MapPost("/register", static ValueTask<IResult> (
|
||||
[AsParameters] Htmx.ApiDemo.Templates.PostRegisterHandler.Command cmd,
|
||||
Htmx.ApiDemo.Templates.PostRegisterHandler.Handler handler,
|
||||
CancellationToken token) => handler.HandleAsync(cmd, token));
|
||||
|
||||
app.MapPost("/logout", static ValueTask<IResult> (
|
||||
[AsParameters] Htmx.ApiDemo.Templates.PostLogoutHandler.Command cmd,
|
||||
Htmx.ApiDemo.Templates.PostLogoutHandler.Handler handler,
|
||||
CancellationToken token) => handler.HandleAsync(cmd, token));
|
||||
|
||||
app.MapGet("/ui-demo", static ValueTask<IResult> (
|
||||
[AsParameters] Htmx.ApiDemo.Templates.GetUiDemoHandler.Query query,
|
||||
Htmx.ApiDemo.Templates.GetUiDemoHandler.Handler handler,
|
||||
CancellationToken token) => handler.HandleAsync(query, token));
|
||||
app.MapHtmxRoutes();
|
||||
|
||||
app.Run();
|
||||
@@ -1,5 +1,3 @@
|
||||
using Immediate.Apis.Shared;
|
||||
using Immediate.Handlers.Shared;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
@@ -18,29 +16,3 @@ public sealed class Greeting : GreetingBase
|
||||
protected override void RenderGreetingId(HtmxRenderContext context) => context.Writer.WriteUtf8(_greetingIdData);
|
||||
protected override void RenderUser(HtmxRenderContext context) => context.Writer.WriteUtf8(_userData);
|
||||
}
|
||||
|
||||
[Handler]
|
||||
[MapGet("/greet/{username}/{count?}/{id?}")]
|
||||
public static partial class GetGreetingHandler
|
||||
{
|
||||
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<IResult> HandleAsync(
|
||||
Query query,
|
||||
IHttpContextAccessor httpContextAccessor,
|
||||
CancellationToken token)
|
||||
{
|
||||
var context = httpContextAccessor.HttpContext
|
||||
?? throw new InvalidOperationException("HttpContext is not available.");
|
||||
|
||||
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));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Htmx.ApiDemo.Templates;
|
||||
|
||||
namespace Htmx.ApiDemo;
|
||||
|
||||
public static partial class RouteMap
|
||||
{
|
||||
public static void MapGetIndex(WebApplication app)
|
||||
=> app.MapGet("/", (IHttpContextAccessor contextAccessor) =>
|
||||
{
|
||||
var context = contextAccessor.HttpContext
|
||||
?? throw new InvalidOperationException("HttpContext is not available.");
|
||||
|
||||
var greet = new Greeting { Username = "Enciphered", Count = 0, GreetingId = Guid.NewGuid() };
|
||||
greet.HtmxAwareWriteToBody(
|
||||
context: context,
|
||||
title: "Home",
|
||||
appName: "HtmxApp",
|
||||
pageTitle: "Home"
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -1,6 +1,4 @@
|
||||
using Htmx.ApiDemo.Data;
|
||||
using Immediate.Apis.Shared;
|
||||
using Immediate.Handlers.Shared;
|
||||
using Microsoft.AspNetCore.Antiforgery;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
@@ -25,59 +23,4 @@ public sealed class Login : LoginBase
|
||||
|
||||
protected override void RenderErrorMessage(HtmxRenderContext ctx) => ctx.Writer.WriteUtf8(_errorData);
|
||||
protected override void RenderAntiforgeryToken(HtmxRenderContext ctx) => ctx.Writer.WriteUtf8(_afTokenData);
|
||||
}
|
||||
|
||||
|
||||
[Handler]
|
||||
[MapGet("/login")]
|
||||
public static partial class GetLoginHandler
|
||||
{
|
||||
public class Query;
|
||||
|
||||
private static ValueTask<IResult> HandleAsync(
|
||||
Query _,
|
||||
IHttpContextAccessor httpContextAccessor,
|
||||
IAntiforgery antiforgery,
|
||||
CancellationToken token)
|
||||
{
|
||||
var ctx = httpContextAccessor.HttpContext
|
||||
?? throw new InvalidOperationException("HttpContext is not available.");
|
||||
|
||||
if (ctx.User.Identity?.IsAuthenticated == true)
|
||||
return ValueTask.FromResult<IResult>(new HtmxResult("/"));
|
||||
|
||||
var afTokens = antiforgery.GetAndStoreTokens(ctx);
|
||||
return ValueTask.FromResult<IResult>(ctx.WriteHtmxPage(new Login(afToken: afTokens.RequestToken), title: "Sign in", appName: "HtmxApp", pageTitle: "Sign in"));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
[Handler]
|
||||
[MapPost("/login")]
|
||||
public static partial class PostLoginHandler
|
||||
{
|
||||
public class Command
|
||||
{
|
||||
[FromForm] public string Email { get; set; } = default!;
|
||||
[FromForm] public string Password { get; set; } = default!;
|
||||
}
|
||||
|
||||
private static async ValueTask<IResult> HandleAsync(
|
||||
[AsParameters] Command command,
|
||||
IHttpContextAccessor httpContextAccessor,
|
||||
IAntiforgery antiforgery,
|
||||
AuthService authService,
|
||||
CancellationToken token)
|
||||
{
|
||||
var ctx = httpContextAccessor.HttpContext
|
||||
?? throw new InvalidOperationException("HttpContext is not available.");
|
||||
|
||||
var (success, error) = await authService.LoginAsync(command.Email, command.Password);
|
||||
|
||||
if (success)
|
||||
return new HtmxResult("/");
|
||||
|
||||
var afTokens = antiforgery.GetAndStoreTokens(ctx);
|
||||
return ctx.WriteHtmxPage(new Login(error, afToken: afTokens.RequestToken), title: "Sign in", appName: "HtmxApp", pageTitle: "Sign in");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Antiforgery;
|
||||
using Htmx.ApiDemo.Templates;
|
||||
using Htmx.ApiDemo.Data;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Htmx.ApiDemo;
|
||||
|
||||
public static partial class RouteMap
|
||||
{
|
||||
private static void GetLogin(WebApplication app)
|
||||
=> app.MapGet("/login", (IHttpContextAccessor contextAccessor, IAntiforgery antiforgery) =>
|
||||
{
|
||||
var context = contextAccessor.HttpContext
|
||||
?? throw new InvalidOperationException("HttpContext is not available.");
|
||||
|
||||
if (context.User.Identity?.IsAuthenticated == true)
|
||||
{
|
||||
context.Response.Redirect("/");
|
||||
return;
|
||||
}
|
||||
|
||||
var afToken = antiforgery.GetAndStoreTokens(context).RequestToken;
|
||||
var loginComponent = new Login(afToken: afToken);
|
||||
loginComponent.HtmxAwareWriteToBody(
|
||||
context: context,
|
||||
title: "Login",
|
||||
appName: "HtmxApp",
|
||||
pageTitle: "Welcome back"
|
||||
);
|
||||
});
|
||||
|
||||
private static void PostLogin(WebApplication app)
|
||||
=> app.MapPost("/login", async ValueTask
|
||||
(
|
||||
[FromForm] string email,
|
||||
[FromForm] string password,
|
||||
[FromServices] IHttpContextAccessor httpContextAccessor,
|
||||
[FromServices] IAntiforgery antiforgery,
|
||||
[FromServices] AppAuthService authService
|
||||
) =>
|
||||
{
|
||||
var context = httpContextAccessor.HttpContext
|
||||
?? throw new InvalidOperationException("HttpContext is not available.");
|
||||
|
||||
var afToken = antiforgery.GetAndStoreTokens(context).RequestToken;
|
||||
|
||||
var (success, error) = await authService.LoginAsync(email, password);
|
||||
|
||||
if (success)
|
||||
{
|
||||
context.Response.Redirect("/");
|
||||
return;
|
||||
}
|
||||
|
||||
var loginComponent = new Login(error, afToken: afToken);
|
||||
loginComponent.HtmxAwareWriteToBody(
|
||||
context: context,
|
||||
title: "Login",
|
||||
appName: "HtmxApp",
|
||||
pageTitle: "Welcome back"
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
using Htmx.ApiDemo;
|
||||
using Htmx.ApiDemo.Data;
|
||||
using Immediate.Apis.Shared;
|
||||
using Immediate.Handlers.Shared;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Htmx.ApiDemo.Templates;
|
||||
|
||||
[Handler]
|
||||
[MapPost("/logout")]
|
||||
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 class Command;
|
||||
|
||||
private static async ValueTask<IResult> HandleAsync(
|
||||
[AsParameters] Command _,
|
||||
AuthService authService,
|
||||
IHttpContextAccessor httpContextAccessor,
|
||||
CancellationToken token)
|
||||
{
|
||||
await authService.SignOutAsync();
|
||||
return new HtmxResult("/login");
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,10 @@
|
||||
using Htmx.ApiDemo;
|
||||
using Htmx.ApiDemo.Templates.Components;
|
||||
using Immediate.Apis.Shared;
|
||||
using Immediate.Handlers.Shared;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
|
||||
namespace Htmx.ApiDemo.Templates;
|
||||
namespace Htmx.ApiDemo;
|
||||
|
||||
public sealed class MainLayout : MainLayoutBase
|
||||
public sealed class MainLayout : Templates.MainLayoutBase
|
||||
{
|
||||
private byte[] _titleData = [];
|
||||
private byte[] _appNameData = [];
|
||||
@@ -67,24 +65,4 @@ public sealed class MainLayout : MainLayoutBase
|
||||
protected override void RenderAppName(HtmxRenderContext context) => context.Writer.WriteUtf8(_appNameData);
|
||||
protected override void RenderPageTitle(HtmxRenderContext context) => context.Writer.WriteUtf8(_pageTitleData);
|
||||
protected override void RenderUserSection(HtmxRenderContext context) => context.Writer.WriteUtf8(_userSectionData);
|
||||
}
|
||||
|
||||
|
||||
[Handler]
|
||||
[MapGet("/")]
|
||||
public static partial class GetIndexHandler
|
||||
{
|
||||
public class Command;
|
||||
|
||||
private static ValueTask<IResult> HandleAsync(
|
||||
Command command,
|
||||
IHttpContextAccessor httpContextAccessor,
|
||||
CancellationToken token)
|
||||
{
|
||||
var context = httpContextAccessor.HttpContext
|
||||
?? throw new InvalidOperationException("HttpContext is not available.");
|
||||
|
||||
var greet = new Greeting { Username = "Enciphered", Count = 0, GreetingId = Guid.NewGuid() };
|
||||
return ValueTask.FromResult<IResult>(context.WriteHtmxPage(greet, title: "Home", appName: "HtmxApp", pageTitle: "Home"));
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,4 @@
|
||||
using Htmx.ApiDemo.Data;
|
||||
using Immediate.Apis.Shared;
|
||||
using Immediate.Handlers.Shared;
|
||||
using Microsoft.AspNetCore.Antiforgery;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
@@ -25,69 +23,4 @@ public sealed class Register : RegisterBase
|
||||
|
||||
protected override void RenderErrorMessage(HtmxRenderContext ctx) => ctx.Writer.WriteUtf8(_errorData);
|
||||
protected override void RenderAntiforgeryToken(HtmxRenderContext ctx) => ctx.Writer.WriteUtf8(_afTokenData);
|
||||
}
|
||||
|
||||
|
||||
[Handler]
|
||||
[MapGet("/register")]
|
||||
public static partial class GetRegisterHandler
|
||||
{
|
||||
public class Query;
|
||||
|
||||
private static ValueTask<IResult> HandleAsync(
|
||||
Query _,
|
||||
IHttpContextAccessor httpContextAccessor,
|
||||
IAntiforgery antiforgery,
|
||||
CancellationToken token)
|
||||
{
|
||||
var ctx = httpContextAccessor.HttpContext
|
||||
?? throw new InvalidOperationException("HttpContext is not available.");
|
||||
|
||||
if (ctx.User.Identity?.IsAuthenticated == true)
|
||||
return ValueTask.FromResult<IResult>(new HtmxResult("/"));
|
||||
|
||||
var afTokens = antiforgery.GetAndStoreTokens(ctx);
|
||||
return ValueTask.FromResult<IResult>(ctx.WriteHtmxPage(new Register(afToken: afTokens.RequestToken), title: "Register", appName: "HtmxApp", pageTitle: "Create account"));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
[Handler]
|
||||
[MapPost("/register")]
|
||||
public static partial class PostRegisterHandler
|
||||
{
|
||||
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<IResult> HandleAsync(
|
||||
[AsParameters] Command command,
|
||||
IHttpContextAccessor httpContextAccessor,
|
||||
IAntiforgery antiforgery,
|
||||
AuthService authService,
|
||||
CancellationToken token)
|
||||
{
|
||||
var ctx = httpContextAccessor.HttpContext
|
||||
?? throw new InvalidOperationException("HttpContext is not available.");
|
||||
|
||||
if (command.Password != command.ConfirmPassword)
|
||||
{
|
||||
var afTokens1 = antiforgery.GetAndStoreTokens(ctx);
|
||||
return ctx.WriteHtmxPage(new Register("Passwords do not match.", afToken: afTokens1.RequestToken),
|
||||
title: "Register", appName: "HtmxApp", pageTitle: "Create account");
|
||||
}
|
||||
|
||||
var (success, error) = await authService.RegisterAsync(command.Email, command.Password, command.DisplayName);
|
||||
|
||||
if (success)
|
||||
return new HtmxResult("/");
|
||||
|
||||
var afTokens2 = antiforgery.GetAndStoreTokens(ctx);
|
||||
return ctx.WriteHtmxPage(new Register(error, afToken: afTokens2.RequestToken),
|
||||
title: "Register", appName: "HtmxApp", pageTitle: "Create account");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Htmx.ApiDemo.Templates;
|
||||
using Microsoft.AspNetCore.Antiforgery;
|
||||
using Htmx.ApiDemo.Data;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Htmx.ApiDemo;
|
||||
|
||||
public static partial class RouteMap
|
||||
{
|
||||
private static void GetRegister(WebApplication app)
|
||||
=> app.MapGet("/register", (IHttpContextAccessor contextAccessor, IAntiforgery antiforgery) =>
|
||||
{
|
||||
var context = contextAccessor.HttpContext
|
||||
?? throw new InvalidOperationException("HttpContext is not available.");
|
||||
|
||||
if (context.User.Identity?.IsAuthenticated == true)
|
||||
{
|
||||
context.Response.Redirect("/");
|
||||
return;
|
||||
}
|
||||
|
||||
var afTokens = antiforgery.GetAndStoreTokens(context);
|
||||
var registerComponent = new Register(afToken: afTokens.RequestToken);
|
||||
registerComponent.HtmxAwareWriteToBody(
|
||||
context: context,
|
||||
title: "Register",
|
||||
appName: "HtmxApp",
|
||||
pageTitle: "Create account"
|
||||
);
|
||||
});
|
||||
|
||||
private static void PostRegister(WebApplication app)
|
||||
=> app.MapPost("/register", async ValueTask
|
||||
(
|
||||
[FromForm] string email,
|
||||
[FromForm] string password,
|
||||
[FromForm] string confirmPassword,
|
||||
[FromForm] string? displayName,
|
||||
[FromServices] IHttpContextAccessor httpContextAccessor,
|
||||
[FromServices] IAntiforgery antiforgery,
|
||||
[FromServices] AppAuthService authService
|
||||
) =>
|
||||
{
|
||||
var context = httpContextAccessor.HttpContext
|
||||
?? throw new InvalidOperationException("HttpContext is not available.");
|
||||
|
||||
var afToken = antiforgery.GetAndStoreTokens(context).RequestToken;
|
||||
|
||||
if (password != confirmPassword)
|
||||
{
|
||||
var errorComponent = new Register("Passwords do not match.", afToken: afToken);
|
||||
errorComponent.HtmxAwareWriteToBody(
|
||||
context: context,
|
||||
title: "Register",
|
||||
appName: "HtmxApp",
|
||||
pageTitle: "Create account"
|
||||
);
|
||||
}
|
||||
|
||||
var (success, error) = await authService.RegisterAsync(email, password, displayName);
|
||||
|
||||
if (success)
|
||||
{
|
||||
context.Response.Redirect("/");
|
||||
return;
|
||||
}
|
||||
|
||||
var registerComponent = new Register(error, afToken: afToken);
|
||||
});
|
||||
}
|
||||
@@ -1,6 +1,4 @@
|
||||
using Htmx.ApiDemo.Templates.Components;
|
||||
using Immediate.Apis.Shared;
|
||||
using Immediate.Handlers.Shared;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
|
||||
namespace Htmx.ApiDemo.Templates;
|
||||
@@ -364,24 +362,4 @@ public sealed class UiDemo : UiDemoBase
|
||||
protected override void RenderDropdownDemo(HtmxRenderContext ctx) => DropdownDemo.Render(ctx);
|
||||
|
||||
protected override void RenderToastViewportDemo(HtmxRenderContext ctx) => ToastViewportDemo.Render(ctx);
|
||||
}
|
||||
|
||||
|
||||
[Handler]
|
||||
[MapGet("/ui-demo")]
|
||||
public static partial class GetUiDemoHandler
|
||||
{
|
||||
public class Query;
|
||||
|
||||
private static ValueTask<IResult> HandleAsync(
|
||||
Query query,
|
||||
IHttpContextAccessor httpContextAccessor,
|
||||
CancellationToken token)
|
||||
{
|
||||
var context = httpContextAccessor.HttpContext
|
||||
?? throw new InvalidOperationException("HttpContext is not available.");
|
||||
|
||||
var page = new UiDemo();
|
||||
return ValueTask.FromResult<IResult>(context.WriteHtmxPage(page, title: "UI Demo", appName: "HtmxApp", pageTitle: "UI Components"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Htmx.ApiDemo.Templates;
|
||||
|
||||
namespace Htmx.ApiDemo;
|
||||
|
||||
public static partial class RouteMap
|
||||
{
|
||||
private static void GetUiDemo(WebApplication app)
|
||||
=> app.MapGet("/ui-demo", (IHttpContextAccessor contextAccessor) =>
|
||||
{
|
||||
var context = contextAccessor.HttpContext
|
||||
?? throw new InvalidOperationException("HttpContext is not available.");
|
||||
|
||||
if (context.User.Identity?.IsAuthenticated == false)
|
||||
{
|
||||
context.Response.Redirect("/login");
|
||||
return;
|
||||
}
|
||||
|
||||
var uiDemoComponent = new UiDemo();
|
||||
uiDemoComponent.HtmxAwareWriteToBody(
|
||||
context: context,
|
||||
title: "UI Demo",
|
||||
appName: "HtmxApp",
|
||||
pageTitle: "Htmx UI Demo"
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -4,5 +4,9 @@
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
}
|
||||
},
|
||||
"ConnectionStrings": {
|
||||
"DefaultConnection": "mongodb://localhost:27017/"
|
||||
},
|
||||
"MongoDbName": "HtmxDemoDb"
|
||||
}
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
<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>
|
||||
Reference in New Issue
Block a user