English
File endpoints
Step 1. Uploads and their size
Why. Files arrive as multipart/form-data, the format of an HTML file input. ASP.NET Core binds the file part to an IFormFile parameter. Two limits protect the server before the business layer checks anything:
- a global limit of 1 MB for every request body (set in
AddApiat the end of this topic): JSON requests are small, and nobody should be able to post a gigabyte to/api/chats; - a per-endpoint limit for uploads, a little above the file limit of the business layer (5 MB for avatars, 20 MB for attachments), so a huge upload is cut off by the server early, while the exact limit is still enforced — with a proper validation error — by
LimitedReadStream(topic 9).
Do.
cs
using Chatex.Core.Common;
using Microsoft.AspNetCore.Mvc;
namespace Chatex.Api.Infrastructure;
internal static class FileUploadExtensions
{
/// <summary>Extra room for the multipart framing around the file itself.</summary>
private const long MultipartOverheadBytes = 64 * 1024;
public static FileUpload ToFileUpload(this IFormFile file) =>
new(file.OpenReadStream(), file.FileName, file.ContentType, file.Length);
/// <summary>
/// Caps the request body a little above <paramref name="maxFileBytes"/>, so huge uploads are cut off early;
/// the business layer still enforces the exact limit and answers with a validation error.
/// Antiforgery is off because these endpoints authenticate with a bearer token, not a cookie.
/// </summary>
public static RouteHandlerBuilder AcceptsFileUpTo(this RouteHandlerBuilder builder, long maxFileBytes)
{
var limit = maxFileBytes + MultipartOverheadBytes;
return builder
.DisableAntiforgery()
.WithMetadata(new RequestSizeLimitAttribute(limit))
.WithFormOptions(multipartBodyLengthLimit: limit);
}
}ToFileUploadturns the ASP.NET CoreIFormFileinto theFileUploadrecord of Chatex.Core — the business layer never sees HTTP types.AcceptsFileUpToraises the body limit for one endpoint withRequestSizeLimitAttributeand the multipart form limit, plus 64 KB for the multipart framing.DisableAntiforgery: form-bound endpoints in ASP.NET Core check an antiforgery token by default, a protection for cookie-authenticated forms. Chatex authenticates with a bearer header that other sites cannot send, so the check is not needed — the comment says why.
Step 2. Images by their bytes
Why. Avatars are stored without their media type (topic 9 stores only the bytes and checks the claimed type). When serving an avatar, the API must say what it is. It sniffs the first bytes: every image format starts with a signature (magic number).
Do.
cs
namespace Chatex.Api.Infrastructure;
/// <summary>Finds an avatar's media type from its first bytes, since only the image itself is stored.</summary>
internal static class ImageSniffer
{
public const string Fallback = "application/octet-stream";
private const int HeaderLength = 12;
/// <summary>Reads the header and returns a stream positioned back at the first byte.</summary>
public static async Task<(Stream Content, string ContentType)> SniffAsync(Stream content, CancellationToken cancellationToken)
{
if (!content.CanSeek)
{
var buffered = new MemoryStream();
await using (content)
{
await content.CopyToAsync(buffered, cancellationToken);
}
content = buffered;
content.Position = 0;
}
var header = new byte[HeaderLength];
var read = await content.ReadAtLeastAsync(header, HeaderLength, throwOnEndOfStream: false, cancellationToken);
content.Position = 0;
return (content, Detect(header.AsSpan(0, read)));
}
public static string Detect(ReadOnlySpan<byte> header) => header switch
{
[0xFF, 0xD8, 0xFF, ..] => "image/jpeg",
[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, ..] => "image/png",
[0x52, 0x49, 0x46, 0x46, _, _, _, _, 0x57, 0x45, 0x42, 0x50, ..] => "image/webp",
_ => Fallback,
};
}- List patterns (C# 11) match the start of a byte span:
[0xFF, 0xD8, 0xFF, ..]is JPEG;[0x52, 0x49, 0x46, 0x46, _, _, _, _, 0x57, 0x45, 0x42, 0x50, ..]isRIFF, four bytes of any size (_), thenWEBP...matches the rest. - A stream that cannot seek is copied into memory first, so the header can be read and the stream rewound.
ReadAtLeastAsyncreads 12 bytes, or fewer for a tiny file without throwing. - Anything unknown is served as
application/octet-stream— the browser will not render it.
Step 3. Downloads that cannot run scripts
Why. Serving user files from your own domain is dangerous: if a browser decides that a "picture" is really HTML, scripts inside it run with the rights of Chatex. Three headers prevent that:
X-Content-Type-Options: nosniff— the browser must trust ourContent-Type, not guess;Content-Disposition: attachment; filename=…for everything that is not an image — the browser downloads it instead of opening it;Cache-Control: private— no shared proxy may keep a copy of a private file.
Do.
cs
using Chatex.Core.Attachments;
using Chatex.Core.Common;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.Net.Http.Headers;
namespace Chatex.Api.Infrastructure;
/// <summary>Streams stored files back. Files are private to their readers, and browsers must not guess their type.</summary>
internal static class FileResults
{
public static async Task<Results<FileStreamHttpResult, ProblemHttpResult>> ToImageAsync(
this Task<Result<Stream>> pending, HttpResponse response, CancellationToken cancellationToken)
{
var result = await pending;
if (!result.IsSuccess)
{
return result.Error.ToProblem();
}
var (content, contentType) = await ImageSniffer.SniffAsync(result.Value, cancellationToken);
SetPrivateHeaders(response);
response.Headers.CacheControl = "private, no-cache";
return TypedResults.Stream(content, contentType);
}
/// <summary>Images open in the browser; everything else downloads under its original name.</summary>
public static FileStreamHttpResult ToFile(Stream content, AttachmentDownload download, HttpResponse response)
{
SetPrivateHeaders(response);
if (!IsImage(download.ContentType))
{
return TypedResults.Stream(content, download.ContentType, download.FileName, enableRangeProcessing: true);
}
response.Headers.ContentDisposition = new ContentDispositionHeaderValue("inline") { FileNameStar = download.FileName }.ToString();
return TypedResults.Stream(content, download.ContentType, enableRangeProcessing: true);
}
private static bool IsImage(string contentType) => contentType.StartsWith("image/", StringComparison.OrdinalIgnoreCase);
private static void SetPrivateHeaders(HttpResponse response)
{
response.Headers.XContentTypeOptions = "nosniff";
response.Headers.CacheControl = "private, max-age=3600";
}
}ToImageAsyncis an extension method on the pending task of the service call, so an avatar endpoint stays a one-liner:profiles.OpenAvatarAsync(id, ct).ToImageAsync(response, ct). Avatars change, sono-cachemakes the browser revalidate them.ToFileopens images inline (with the file name infilename*, which allows non-ASCII names) and offers everything else as a download under its original name.enableRangeProcessinglets a video player request a part of the file.
Step 4. The endpoints
Do. Create the attachment endpoints:
cs
using System.Security.Claims;
using Chatex.Api.Infrastructure;
using Chatex.Core.Attachments;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.Extensions.Options;
namespace Chatex.Api.Endpoints;
internal static class AttachmentEndpoints
{
public static void MapAttachmentEndpoints(this IEndpointRouteBuilder routes)
{
var maxBytes = routes.ServiceProvider.GetRequiredService<IOptions<AttachmentOptions>>().Value.MaxBytes;
var group = routes.MapGroup("/attachments").WithTags("Attachments");
group.MapPost("", UploadAsync).WithName("UploadAttachment").AcceptsFileUpTo(maxBytes)
.WithSummary("Stores a file; pass its id in attachmentIds when sending the message.");
group.MapGet("/{id:guid}", DownloadAsync).WithName("DownloadAttachment")
.WithSummary("For the uploader and anyone who can see the chat the file was sent to.");
}
private static async Task<Results<Created<AttachmentDto>, ProblemHttpResult>> UploadAsync(
IFormFile file, ClaimsPrincipal user, IAttachmentService attachments, CancellationToken cancellationToken) =>
(await attachments.UploadAsync(user.GetUserId(), file.ToFileUpload(), cancellationToken))
.ToCreated(a => $"/api/attachments/{a.Id}");
private static async Task<Results<FileStreamHttpResult, ProblemHttpResult>> DownloadAsync(
Guid id, ClaimsPrincipal user, IAttachmentService attachments, HttpResponse response, CancellationToken cancellationToken)
{
var result = await attachments.GetDownloadAsync(user.GetUserId(), id, cancellationToken);
if (!result.IsSuccess)
{
return result.Error.ToProblem();
}
var content = await attachments.OpenReadAsync(result.Value, cancellationToken);
return FileResults.ToFile(content, result.Value, response);
}
}The upload limit is read once, when the endpoints are mapped, from the validated AttachmentOptions of topic 11; routes.ServiceProvider is the application's container.
Add the avatar endpoints to the three files of topic 12 (new lines in green):
cs
using System.Security.Claims;
using Chatex.Api.Infrastructure;
using Chatex.Core.Common;
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.");
group.MapPut("/avatar", SetAvatarAsync).WithName("SetMyAvatar").AcceptsFileUpTo(AvatarLimits.MaxBytes);
group.MapDelete("/avatar", RemoveAvatarAsync).WithName("RemoveMyAvatar");
}
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();
}
private static async Task<Results<Ok<MyProfileDto>, ProblemHttpResult>> SetAvatarAsync(
IFormFile file, ClaimsPrincipal user, IProfileService profiles, CancellationToken cancellationToken) =>
(await profiles.SetAvatarAsync(user.GetUserId(), file.ToFileUpload(), cancellationToken)).ToOk();
private static async Task<Results<Ok<MyProfileDto>, ProblemHttpResult>> RemoveAvatarAsync(
ClaimsPrincipal user, IProfileService profiles, CancellationToken cancellationToken) =>
(await profiles.RemoveAvatarAsync(user.GetUserId(), cancellationToken)).ToOk();
}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");
group.MapGet("/{id:guid}/avatar", GetAvatarAsync).WithName("GetUserAvatar");
}
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();
private static Task<Results<FileStreamHttpResult, ProblemHttpResult>> GetAvatarAsync(
Guid id, IProfileService profiles, HttpResponse response, CancellationToken cancellationToken) =>
profiles.OpenAvatarAsync(id, cancellationToken).ToImageAsync(response, cancellationToken);
}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.MapGet("/{id:guid}/avatar", GetAvatarAsync).WithName("GetChatAvatar");
group.MapPut("/{id:guid}/avatar", SetAvatarAsync).WithName("SetChatAvatar").AcceptsFileUpTo(AvatarLimits.MaxBytes);
group.MapDelete("/{id:guid}/avatar", RemoveAvatarAsync).WithName("RemoveChatAvatar");
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 Task<Results<FileStreamHttpResult, ProblemHttpResult>> GetAvatarAsync(
Guid id, ClaimsPrincipal user, IChatService chats, HttpResponse response, CancellationToken cancellationToken) =>
chats.OpenAvatarAsync(user.GetUserId(), id, cancellationToken).ToImageAsync(response, cancellationToken);
private static async Task<Results<Ok<ChatDto>, ProblemHttpResult>> SetAvatarAsync(
Guid id, IFormFile file, ClaimsPrincipal user, IChatService chats, CancellationToken cancellationToken) =>
(await chats.SetAvatarAsync(user.GetUserId(), id, file.ToFileUpload(), cancellationToken)).ToOk();
private static async Task<Results<Ok<ChatDto>, ProblemHttpResult>> RemoveAvatarAsync(
Guid id, ClaimsPrincipal user, IChatService chats, CancellationToken cancellationToken) =>
(await chats.RemoveAvatarAsync(user.GetUserId(), id, cancellationToken)).ToOk();
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();
}The avatar of a chat requires the caller to see the chat (the service checks visibility); the avatar of a user is visible to every signed-in user.
Check
dotnet build succeeds. The new endpoints are mapped in Program.cs in Operations.