English
Endpoint groups
Step 1. One file per area
Why. Each area of the API — the own profile, other users, chats, messages — gets one static class with a Map…Endpoints method and one small private method per endpoint. A route group (MapGroup("/chats")) gives all its endpoints a common prefix, a tag for OpenAPI and, later, common rules such as rate limiting. The file then reads like a table of routes at the top, followed by the implementations.
The avatar and attachment endpoints need file handling; they come in topic 13. Everything else is mapped now.
Step 2. Profile and users
Do.
cs
using System.Security.Claims;
using Chatex.Api.Infrastructure;
using Chatex.Core.Users;
using Microsoft.AspNetCore.Http.HttpResults;
namespace Chatex.Api.Endpoints;
/// <summary>The signed-in user's own account under <c>/api/me</c>.</summary>
internal static class ProfileEndpoints
{
public static void MapProfileEndpoints(this IEndpointRouteBuilder routes)
{
var group = routes.MapGroup("/me").WithTags("Profile");
group.MapGet("", GetAsync).WithName("GetMyProfile");
group.MapPut("", UpdateAsync).WithName("UpdateMyProfile");
group.MapPut("/password", ChangePasswordAsync).WithName("ChangePassword")
.WithSummary("Changes the password and ends every session, this one included.");
}
private static async Task<Results<Ok<MyProfileDto>, ProblemHttpResult>> GetAsync(
ClaimsPrincipal user, IProfileService profiles, CancellationToken cancellationToken) =>
(await profiles.GetMyProfileAsync(user.GetUserId(), cancellationToken)).ToOk();
private static async Task<Results<Ok<MyProfileDto>, ProblemHttpResult>> UpdateAsync(
UpdateProfileCommand command, ClaimsPrincipal user, IProfileService profiles, CancellationToken cancellationToken) =>
(await profiles.UpdateProfileAsync(user.GetUserId(), command, cancellationToken)).ToOk();
private static async Task<Results<NoContent, ProblemHttpResult>> ChangePasswordAsync(
ChangePasswordCommand command, ClaimsPrincipal user, IProfileService profiles, HttpResponse response,
CancellationToken cancellationToken)
{
var result = await profiles.ChangePasswordAsync(user.GetUserId(), command, cancellationToken);
if (result.IsSuccess)
{
RefreshTokenCookie.Clear(response);
}
return result.ToNoContent();
}
}The own profile lives under /api/me: the client never has to know its own id. Changing the password ends every session (topic 9), this browser's too, so the endpoint also clears the refresh cookie.
cs
using Chatex.Api.Infrastructure;
using Chatex.Core.Users;
using Microsoft.AspNetCore.Http.HttpResults;
namespace Chatex.Api.Endpoints;
internal static class UserEndpoints
{
public static void MapUserEndpoints(this IEndpointRouteBuilder routes)
{
var group = routes.MapGroup("/users").WithTags("Users");
group.MapGet("", SearchAsync).WithName("SearchUsers")
.WithSummary("Finds users by user name or display name (at least 2 characters).");
group.MapGet("/{id:guid}", GetAsync).WithName("GetUser");
}
private static async Task<Results<Ok<UserSummaryDto[]>, ProblemHttpResult>> SearchAsync(
string? query, int? limit, IProfileService profiles, CancellationToken cancellationToken) =>
(await profiles.SearchUsersAsync(query ?? "", limit, cancellationToken)).ToOk();
private static async Task<Results<Ok<UserDto>, ProblemHttpResult>> GetAsync(
Guid id, IProfileService profiles, CancellationToken cancellationToken) =>
(await profiles.GetUserAsync(id, cancellationToken)).ToOk();
}Route constraints: {id:guid} matches only a GUID. /api/users/abc does not reach the endpoint at all and answers 404.
Step 3. Chats
Do.
cs
using System.Security.Claims;
using Chatex.Api.Contracts;
using Chatex.Api.Infrastructure;
using Chatex.Core.Chats;
using Chatex.Core.Common;
using Microsoft.AspNetCore.Http.HttpResults;
namespace Chatex.Api.Endpoints;
internal static class ChatEndpoints
{
public static void MapChatEndpoints(this IEndpointRouteBuilder routes)
{
var group = routes.MapGroup("/chats").WithTags("Chats");
group.MapGet("", GetMyChatsAsync).WithName("GetMyChats")
.WithSummary("The caller's chats, most recently active first.");
group.MapPost("", CreateAsync).WithName("CreateChat").WithSummary("Creates a group or channel.");
group.MapPost("/direct", OpenDirectAsync).WithName("OpenDirectChat")
.WithSummary("Returns the direct chat with a user, creating it on first use.");
group.MapGet("/search", SearchAsync).WithName("SearchPublicChats");
group.MapGet("/{id:guid}", GetAsync).WithName("GetChat");
group.MapPut("/{id:guid}", UpdateAsync).WithName("UpdateChat");
group.MapDelete("/{id:guid}", DeleteAsync).WithName("DeleteChat");
group.MapPost("/{id:guid}/join", JoinAsync).WithName("JoinChat");
group.MapPost("/{id:guid}/leave", LeaveAsync).WithName("LeaveChat");
group.MapGet("/{id:guid}/members", GetMembersAsync).WithName("GetChatMembers");
group.MapPost("/{id:guid}/members", AddMembersAsync).WithName("AddChatMembers");
group.MapDelete("/{id:guid}/members/{userId:guid}", RemoveMemberAsync).WithName("RemoveChatMember");
group.MapPut("/{id:guid}/members/{userId:guid}/role", ChangeRoleAsync).WithName("ChangeChatMemberRole")
.WithSummary("Owner only. Making someone the owner transfers ownership.");
group.MapPut("/{id:guid}/mute", SetMutedAsync).WithName("SetChatMuted");
group.MapPost("/{id:guid}/read", MarkReadAsync).WithName("MarkChatRead")
.WithSummary("Moves the caller's read position forward to a message.");
}
private static async Task<Results<Ok<PageDto<ChatListItemDto>>, ProblemHttpResult>> GetMyChatsAsync(
string? cursor, int? limit, ClaimsPrincipal user, IChatService chats, CancellationToken cancellationToken) =>
(await chats.GetMyChatsAsync(user.GetUserId(), cursor, limit, cancellationToken)).ToOk();
private static async Task<Results<Created<ChatDto>, ProblemHttpResult>> CreateAsync(
CreateChatCommand command, ClaimsPrincipal user, IChatService chats, CancellationToken cancellationToken) =>
(await chats.CreateAsync(user.GetUserId(), command, cancellationToken)).ToCreated(c => $"/api/chats/{c.Id}");
private static async Task<Results<Ok<ChatDto>, ProblemHttpResult>> OpenDirectAsync(
OpenDirectRequest request, ClaimsPrincipal user, IChatService chats, CancellationToken cancellationToken) =>
(await chats.OpenDirectAsync(user.GetUserId(), request.UserId, cancellationToken)).ToOk();
private static async Task<Results<Ok<ChatSummaryDto[]>, ProblemHttpResult>> SearchAsync(
string? query, int? limit, IChatService chats, CancellationToken cancellationToken) =>
(await chats.SearchPublicAsync(query ?? "", limit, cancellationToken)).ToOk();
private static async Task<Results<Ok<ChatDto>, ProblemHttpResult>> GetAsync(
Guid id, ClaimsPrincipal user, IChatService chats, CancellationToken cancellationToken) =>
(await chats.GetAsync(user.GetUserId(), id, cancellationToken)).ToOk();
private static async Task<Results<Ok<ChatDto>, ProblemHttpResult>> UpdateAsync(
Guid id, UpdateChatCommand command, ClaimsPrincipal user, IChatService chats, CancellationToken cancellationToken) =>
(await chats.UpdateAsync(user.GetUserId(), id, command, cancellationToken)).ToOk();
private static async Task<Results<NoContent, ProblemHttpResult>> DeleteAsync(
Guid id, ClaimsPrincipal user, IChatService chats, CancellationToken cancellationToken) =>
(await chats.DeleteAsync(user.GetUserId(), id, cancellationToken)).ToNoContent();
private static async Task<Results<Ok<ChatDto>, ProblemHttpResult>> JoinAsync(
Guid id, ClaimsPrincipal user, IChatService chats, CancellationToken cancellationToken) =>
(await chats.JoinAsync(user.GetUserId(), id, cancellationToken)).ToOk();
private static async Task<Results<NoContent, ProblemHttpResult>> LeaveAsync(
Guid id, ClaimsPrincipal user, IChatService chats, CancellationToken cancellationToken) =>
(await chats.LeaveAsync(user.GetUserId(), id, cancellationToken)).ToNoContent();
private static async Task<Results<Ok<PageDto<ChatMemberDto>>, ProblemHttpResult>> GetMembersAsync(
Guid id, string? cursor, int? limit, ClaimsPrincipal user, IChatService chats, CancellationToken cancellationToken) =>
(await chats.GetMembersAsync(user.GetUserId(), id, cursor, limit, cancellationToken)).ToOk();
private static async Task<Results<Ok<AddMembersResponse>, ProblemHttpResult>> AddMembersAsync(
Guid id, AddMembersRequest request, ClaimsPrincipal user, IChatService chats, CancellationToken cancellationToken)
{
var result = await chats.AddMembersAsync(user.GetUserId(), id, request.UserIds ?? [], cancellationToken);
return result.IsSuccess ? TypedResults.Ok(new AddMembersResponse(result.Value)) : result.Error.ToProblem();
}
private static async Task<Results<NoContent, ProblemHttpResult>> RemoveMemberAsync(
Guid id, Guid userId, ClaimsPrincipal user, IChatService chats, CancellationToken cancellationToken) =>
(await chats.RemoveMemberAsync(user.GetUserId(), id, userId, cancellationToken)).ToNoContent();
private static async Task<Results<NoContent, ProblemHttpResult>> ChangeRoleAsync(
Guid id, Guid userId, ChangeRoleRequest request, ClaimsPrincipal user, IChatService chats,
CancellationToken cancellationToken) =>
(await chats.ChangeRoleAsync(user.GetUserId(), id, userId, request.Role, cancellationToken)).ToNoContent();
private static async Task<Results<NoContent, ProblemHttpResult>> SetMutedAsync(
Guid id, SetMutedRequest request, ClaimsPrincipal user, IChatService chats, CancellationToken cancellationToken) =>
(await chats.SetMutedAsync(user.GetUserId(), id, request.Muted, cancellationToken)).ToNoContent();
private static async Task<Results<NoContent, ProblemHttpResult>> MarkReadAsync(
Guid id, MarkReadRequest request, ClaimsPrincipal user, IChatService chats, CancellationToken cancellationToken) =>
(await chats.MarkReadAsync(user.GetUserId(), id, request.MessageId, cancellationToken)).ToNoContent();
}- REST-style routes: the collection
/api/chats(GETlists,POSTcreates), one chat/api/chats/{id}(GET,PUT,DELETE), sub-resources such as/membersand/members/{userId}/role. Actions that are not plain reads or writes becomePOSTto a verb:/join,/leave,/read. /directand/searchare declared before/{id:guid}; the constraint keeps them apart anyway.- Query parameters such as
string? cursor, int? limitare bound from the query string by name:GET /api/chats?limit=20&cursor=…. CreateAsyncanswers201 Createdwith aLocationheader pointing to the new chat.AddMembersAsyncwraps the number inAddMembersResponse, so the body is an object:{ "added": 2 }.
Step 4. Messages
Do.
cs
using System.Security.Claims;
using Chatex.Api.Infrastructure;
using Chatex.Core.Common;
using Chatex.Core.Messages;
using Microsoft.AspNetCore.Http.HttpResults;
namespace Chatex.Api.Endpoints;
internal static class MessageEndpoints
{
public static void MapMessageEndpoints(this IEndpointRouteBuilder routes)
{
var history = routes.MapGroup("/chats/{chatId:guid}/messages").WithTags("Messages");
history.MapGet("", GetHistoryAsync).WithName("GetMessages")
.WithSummary("A page of history: newest first, `before` for older pages, `after` to catch up (oldest first).");
history.MapPost("", SendAsync).WithName("SendMessage");
var messages = routes.MapGroup("/messages").WithTags("Messages");
messages.MapPut("/{id:guid}", EditAsync).WithName("EditMessage").WithSummary("Only the sender can edit.");
messages.MapDelete("/{id:guid}", DeleteAsync).WithName("DeleteMessage")
.WithSummary("The sender or a chat admin can delete; a placeholder stays.");
}
private static async Task<Results<Ok<PageDto<MessageDto>>, ProblemHttpResult>> GetHistoryAsync(
Guid chatId, string? before, string? after, int? limit, ClaimsPrincipal user, IMessageService messages,
CancellationToken cancellationToken) =>
(await messages.GetHistoryAsync(user.GetUserId(), chatId, before, after, limit, cancellationToken)).ToOk();
private static async Task<Results<Created<MessageDto>, ProblemHttpResult>> SendAsync(
Guid chatId, SendMessageCommand command, ClaimsPrincipal user, IMessageService messages,
CancellationToken cancellationToken) =>
(await messages.SendAsync(user.GetUserId(), chatId, command, cancellationToken)).ToCreated(_ => null);
private static async Task<Results<Ok<MessageDto>, ProblemHttpResult>> EditAsync(
Guid id, EditMessageCommand command, ClaimsPrincipal user, IMessageService messages, CancellationToken cancellationToken) =>
(await messages.EditAsync(user.GetUserId(), id, command, cancellationToken)).ToOk();
private static async Task<Results<NoContent, ProblemHttpResult>> DeleteAsync(
Guid id, ClaimsPrincipal user, IMessageService messages, CancellationToken cancellationToken) =>
(await messages.DeleteAsync(user.GetUserId(), id, cancellationToken)).ToNoContent();
}Two groups in one file: the history and sending belong to a chat (/api/chats/{chatId}/messages), editing and deleting address a message directly (/api/messages/{id}), because the message id is enough to find its chat. A sent message answers 201 without a Location — a single message has no GET of its own; ToCreated(_ => null) says so.
Check
dotnet build succeeds. The endpoints are complete but not mapped yet: that is the job of Program.cs, next.