32 lines
1.1 KiB
C#
32 lines
1.1 KiB
C#
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;
|
|
}
|
|
}
|