46 lines
1.9 KiB
C#
46 lines
1.9 KiB
C#
using Immediate.Apis.Shared;
|
|
using Immediate.Handlers.Shared;
|
|
using Microsoft.AspNetCore.Http;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
|
|
namespace Htmx.ApiDemo.Templates;
|
|
|
|
public sealed class Greeting : GreetingBase
|
|
{
|
|
private byte[] _userData = [];
|
|
private byte[] _countData = [];
|
|
private byte[] _greetingIdData = [];
|
|
public required string Username { init => _userData = value.ToUtf8Bytes(); }
|
|
public required int Count { init => _countData = $"{value}".ToUtf8Bytes(); }
|
|
public required Guid GreetingId { init => _greetingIdData = $"{value}".ToUtf8Bytes(); }
|
|
|
|
protected override void RenderCount(HtmxRenderContext context) => context.Writer.WriteUtf8(_countData);
|
|
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));
|
|
}
|
|
} |