English
From results to HTTP
Step 1. Minimal APIs
Why. ASP.NET Core offers two styles of HTTP endpoints: controllers (classes with action methods and attributes) and Minimal APIs (a route mapped directly to a delegate). Chatex uses Minimal APIs: an endpoint is a route plus a small static method whose parameters ASP.NET Core fills from the route, the query string, the JSON body, the services and the request itself:
cs
group.MapGet("/{id:guid}", GetAsync);
static async Task<Results<Ok<ChatDto>, ProblemHttpResult>> GetAsync(
Guid id, ClaimsPrincipal user, IChatService chats, CancellationToken cancellationToken) => ...id comes from the route, user is the signed-in user, chats is resolved from dependency injection, cancellationToken is cancelled when the client disconnects. Because the business layer already does all the work, each endpoint is one or two lines: call a service, turn the result into HTTP. The C# course introduces both styles in REST APIs.
Step 2. Status codes and Problem Details
Why. Every failure of the API must look the same to a client, so the Angular app can handle all of them in one place. HTTP has a standard for that: Problem Details (RFC 9457), a JSON body with the media type application/problem+json:
json
{
"type": "https://tools.ietf.org/html/rfc9110#section-15.5.10",
"title": "Conflict",
"status": 409,
"detail": "This public handle is already taken.",
"code": "handle_taken"
}status, title, detail and type are standard; code is an extension that carries the stable error code of topic 7. A validation error adds errors, a dictionary of field names and messages.
Do. Create the folder Infrastructure in Chatex.Api:
cs
using Chatex.Core.Common;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
namespace Chatex.Api.Infrastructure;
/// <summary>Turns business <see cref="Result"/>s into HTTP results; failures become RFC 9457 problem details.</summary>
internal static class ResultHttpExtensions
{
/// <summary>The problem details extension that carries <see cref="Error.Code"/>.</summary>
public const string CodeExtension = "code";
public static int ToStatusCode(this ErrorKind kind) => kind switch
{
ErrorKind.Validation => StatusCodes.Status400BadRequest,
ErrorKind.NotFound => StatusCodes.Status404NotFound,
ErrorKind.Forbidden => StatusCodes.Status403Forbidden,
ErrorKind.Conflict => StatusCodes.Status409Conflict,
ErrorKind.Unauthorized => StatusCodes.Status401Unauthorized,
_ => throw new ArgumentOutOfRangeException(nameof(kind), kind, null),
};
public static ProblemHttpResult ToProblem(this Error error)
{
ProblemDetails problem = error.Details is { Count: > 0 } details
? new HttpValidationProblemDetails(details.ToDictionary()) { Title = "One or more fields are invalid." }
: new ProblemDetails();
problem.Status = error.Kind.ToStatusCode();
problem.Detail = error.Message;
problem.Extensions[CodeExtension] = error.Code;
return TypedResults.Problem(problem);
}
public static Results<Ok<T>, ProblemHttpResult> ToOk<T>(this Result<T> result) =>
result.IsSuccess ? TypedResults.Ok(result.Value) : result.Error.ToProblem();
/// <param name="location">The new resource's URL, or null when it has no URL of its own.</param>
public static Results<Created<T>, ProblemHttpResult> ToCreated<T>(this Result<T> result, Func<T, string?> location) =>
result.IsSuccess ? TypedResults.Created(location(result.Value), result.Value) : result.Error.ToProblem();
public static Results<NoContent, ProblemHttpResult> ToNoContent(this Result result) =>
result.IsSuccess ? TypedResults.NoContent() : result.Error.ToProblem();
}ToStatusCodemaps eachErrorKindto its status with a switch expression; an unknown kind is a bug and throws.ToProblembuildsHttpValidationProblemDetails(witherrors) when the error has details, plainProblemDetailsotherwise, and adds thecodeextension.ToOk,ToCreated,ToNoContentturn aResultinto one of two results. The return typeResults<Ok<T>, ProblemHttpResult>is a typed union: the endpoint declares exactly which responses it can produce, and OpenAPI reads them from the signature (Step 4 of The composition root).
Step 3. Who is calling, and from where
Why. Almost every endpoint needs the id of the signed-in user. It is the sub claim of the access token (topic 8); a small extension method reads it from the ClaimsPrincipal that the authentication middleware creates. The auth endpoints also record the browser and IP of a new session.
Do.
cs
using System.Security.Claims;
using Microsoft.IdentityModel.JsonWebTokens;
namespace Chatex.Api.Infrastructure;
internal static class ClaimsPrincipalExtensions
{
/// <summary>The signed-in user's id from the access token's <c>sub</c> claim. Only call it on authorized endpoints.</summary>
public static Guid GetUserId(this ClaimsPrincipal user) =>
Guid.TryParse(user.FindFirstValue(JwtRegisteredClaimNames.Sub), out var id)
? id
: throw new InvalidOperationException("The request has no authenticated user id.");
}cs
using Chatex.Core.Auth;
namespace Chatex.Api.Infrastructure;
internal static class HttpContextExtensions
{
/// <summary>Where the request came from. The IP is the client's once forwarded headers are applied.</summary>
public static ClientInfo GetClientInfo(this HttpContext context)
{
var userAgent = context.Request.Headers.UserAgent.ToString();
return new ClientInfo(
string.IsNullOrEmpty(userAgent) ? null : userAgent,
context.Connection.RemoteIpAddress?.ToString());
}
}GetUserId throws if there is no valid id: it is only called on endpoints that require authorization, so a missing id would be a bug in the configuration, not a client error.
Step 4. Contracts of the API
Why. Most request bodies are the commands of the business layer (RegisterCommand, SendMessageCommand, …) and most responses are its DTOs. A few shapes exist only on the HTTP side: the sign-in response without the refresh token (it travels in a cookie), and small bodies for a single value such as { "userId": "…" }.
Do. Create the folder Contracts:
cs
using Chatex.Core.Auth;
using Chatex.Core.Users;
using Chatex.Data.Entities;
namespace Chatex.Api.Contracts;
/// <summary>
/// A signed-in session as the client sees it. The refresh token is not here: it travels in the
/// <c>chatex_refresh</c> HttpOnly cookie, which only <c>/api/auth</c> receives.
/// </summary>
public sealed record AuthResponse(string AccessToken, DateTimeOffset AccessTokenExpiresAt, MyProfileDto User)
{
public static AuthResponse From(AuthResult auth) => new(auth.AccessToken, auth.AccessTokenExpiresAt, auth.User);
}
public sealed record OpenDirectRequest(Guid UserId);
public sealed record AddMembersRequest(IReadOnlyList<Guid>? UserIds);
/// <param name="Added">How many of the users were not members yet.</param>
public sealed record AddMembersResponse(int Added);
public sealed record ChangeRoleRequest(ChatMemberRole Role);
public sealed record SetMutedRequest(bool Muted);
public sealed record MarkReadRequest(Guid MessageId);Why a record for one value? A JSON body should always be an object: { "muted": true } can grow a second property later without breaking clients, a bare true cannot.
Check
dotnet build succeeds. Program.cs is still the template of topic 2; the new classes are not used yet.