Tooark.AspNetCore 5.0.0

dotnet add package Tooark.AspNetCore --version 5.0.0
                    
NuGet\Install-Package Tooark.AspNetCore -Version 5.0.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Tooark.AspNetCore" Version="5.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Tooark.AspNetCore" Version="5.0.0" />
                    
Directory.Packages.props
<PackageReference Include="Tooark.AspNetCore" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Tooark.AspNetCore --version 5.0.0
                    
#r "nuget: Tooark.AspNetCore, 5.0.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Tooark.AspNetCore@5.0.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Tooark.AspNetCore&version=5.0.0
                    
Install as a Cake Addin
#tool nuget:?package=Tooark.AspNetCore&version=5.0.0
                    
Install as a Cake Tool

Tooark.AspNetCore

Library that concentrates the ASP.NET Core specific pieces of Tooark, keeping the general-purpose packages free of the runtime requirement. Packages whose purpose is to integrate with ASP.NET Core (Tooark.Dtos, Tooark.Observability, Tooark.Securities.OpenId) declare the shared framework themselves.

πŸ“– Docs: Tooark.AspNetCore on the site Β· All packages Β· API reference

🌍 Languages: πŸ‡ΊπŸ‡Έ English (this file) Β· πŸ‡§πŸ‡· PortuguΓͺs


πŸ“‘ Contents


πŸ“– Overview

The Tooark.AspNetCore package provides:

  • extensions for ASP.NET Core types: the ModelStateDictionary and IFormFile;
  • conversion and validation of uploaded files, with the IFormFile extensions of FormFileExtension;
  • the ResponseDto body for validation failures in [ApiController] controllers, with AddTooarkModelStateEnvelope;
  • MVC validation of the Tooark.Attributes attributes without the duplicated missing-field message, with AddTooarkValidationAttributes;
  • Problem Details (RFC 9457) for the Tooark.Exceptions exceptions, in controllers and minimal APIs, with AddTooarkProblemDetails;
  • results for minimal APIs that answer a notification or an exception with the same Problem Details, with TooarkResults;
  • the tenant of each request, resolved once from the signed-in user and mapped to the internal tenant id, with AddTooarkTenant and UseTooarkTenant;
  • the place where the ASP.NET Core requirement was moved to, taking it out of the general-purpose packages;
  • integration with the Tooark.Extensions localizer, translating the validation error keys;
  • the home of the family's filters and middlewares.

Why the package exists. Microsoft.AspNetCore.App is not an ordinary NuGet dependency: declaring it makes the application require the ASP.NET Core runtime to be installed, and that requirement is contagious β€” it propagates to every package that references it, and to whoever references those.

Until v3 the requirement came from Tooark.Extensions, because of a single file. In practice, a worker service or a command-line tool that used Tooark.ValueObjects got Microsoft.AspNetCore.App in its own runtimeconfig.json and would not start on a mcr.microsoft.com/dotnet/runtime image.

From v4 on the requirement lives here. Web projects reference this package; the others do not pay for it.

Package Requires the ASP.NET Core runtime
Tooark.AspNetCore yes β€” it is its purpose
Tooark.Dtos yes β€” SearchDto, PaginationDto and ResponseDto use MVC and Http types
Tooark.Observability, Tooark.Securities and Tooark.Securities.OpenId yes β€” they integrate with ASP.NET Core (Tooark.Securities through Microsoft.AspNetCore.Authentication.JwtBearer)
Tooark (aggregator) yes β€” by referencing the packages above
Tooark.Extensions, Tooark.Utils, Tooark.ValueObjects, Tooark.Entities, Tooark.Attributes and the rest no

πŸ”§ Installation

dotnet add package Tooark.AspNetCore

GetErrors and the IFormFile extensions are extension methods and work without configuration. The validation response and the attribute validation have a registration, and both are opt-in: neither the package nor the AddTooarkService of the Tooark aggregator turns them on by itself. The response changes the body of every validation failure in the API, and the attribute validation changes the messages of a missing field.

using Tooark.AspNetCore.Injections;

builder.Services.AddControllers();
builder.Services.AddTooarkModelStateEnvelope();
builder.Services.AddTooarkValidationAttributes();

The Problem Details for exceptions is opt-in as well, and needs the UseExceptionHandler middleware in the pipeline, without arguments:

using Tooark.AspNetCore.Injections;

builder.Services.AddTooarkProblemDetails();

var app = builder.Build();
app.UseExceptionHandler();

The tenant resolution is opt-in too, and needs the UseTooarkTenant middleware after the authentication:

using Tooark.AspNetCore.Injections;
using Tooark.AspNetCore.Middlewares;

builder.Services.AddTooarkTenant();

var app = builder.Build();
app.UseAuthentication();
app.UseTooarkTenant();
app.UseAuthorization();

Runtime requirement: because it declares the shared framework, whoever consumes this package needs the ASP.NET Core runtime installed. In a Docker image, use mcr.microsoft.com/dotnet/aspnet instead of mcr.microsoft.com/dotnet/runtime. A web application already uses that image, so in practice nothing changes.


πŸ“¦ Components

ModelState extensions

  • ModelStateExtension.GetErrors(ModelStateDictionary): returns the ModelState error messages.

Walks every entry of the ModelStateDictionary and gathers the ErrorMessage of each error into a single list. A field with more than one error contributes all of its messages, together and in the order they were recorded. Between fields, the order is the ModelStateDictionary's: it comes from the keys, not from the order in which the fields were validated, but it is not alphabetical either β€” today, top-level fields come before nested ones and shorter keys before longer ones (Cpf before Email). Do not rely on the position of an error in the list.

An error without text β€” recorded with just an exception, or with a blank message β€” becomes the key Field.Invalid;{key}, or BadRequest when it is not tied to a field. ASP.NET Core records errors with just an exception when the exception message is not safe for the client β€” a malformed JSON body with AllowInputFormatterExceptionMessages = false, for instance β€” and when MaxModelValidationErrors is reached. The exception message is never used. Up to v4.5.0 these errors came back with their empty or blank text.

Validation response

  • TooarkDependencyInjection.AddTooarkModelStateEnvelope(IServiceCollection): makes a validation failure in an [ApiController] controller answer with a ResponseDto<object>, instead of ASP.NET Core's ValidationProblemDetails.

In a controller with [ApiController], ASP.NET Core checks the ModelState before the action runs and, when it is invalid, answers 400 with the body built by ApiBehaviorOptions.InvalidModelStateResponseFactory. The method replaces that factory with one that answers 400 with a ResponseDto<object>: Data null and Errors with the messages of GetErrors, already translated by the ResponseDto itself. Keys become text, and the model binding messages arrive unchanged.

What changes for the client:

ValidationProblemDetails (ASP.NET Core default) ResponseDto<object> (with the envelope)
Content type application/problem+json application/json
Errors per field: {"Email": ["..."]}, not translated a single list: ["..."], translated
Other fields type, title, status, traceId data, pagination, metadata

With AddTooarkProblemDetails, the ASP.NET Core column comes out with the Tooark errors list, translated, unless ConvertValidationProblems is turned off.

The envelope does not choose the messages. It changes the body of the response, not what validation records in the ModelState. With <Nullable>enable</Nullable>, a non-nullable field with a Tooark.Attributes attribute arrives missing with two messages: the Field.Required key, translated, and the The Email field is required. of the [Required] that MVC infers, which is not a translation key and arrives as the framework writes it. That is a defect of neither the envelope nor the attribute: the framework's message is removed by AddTooarkValidationAttributes, a separate registration. An application that validates its DTOs with the Tooark attributes calls both.

Registration order does not matter. AddControllers sets the default factory while the options are being built, and would win if it came after a plain Configure. The envelope is applied after every configuration (PostConfigure), so it wins whether it is registered before or after AddControllers. For the same reason, a factory of the application's own set with ConfigureApiBehaviorOptions is replaced: an application that needs its own factory does not call this method. Calling it twice is harmless.

Where it does not apply. Only where ASP.NET Core calls the factory:

  • controllers without [ApiController], which have no automatic check: use GetErrors in the action or a filter;
  • SuppressModelStateInvalidFilter = true, which turns the automatic check off;
  • minimal APIs, which have no ModelState.

OpenAPI. The method changes the response, not the API description. A [ProducesResponseType(400)] without a type is still documented as ProblemDetails, the error type ASP.NET Core assumes for [ApiController]. To make the documentation match the response, declare the error type once in the project with the controllers:

using Microsoft.AspNetCore.Mvc;
using Tooark.Dtos;

[assembly: ProducesErrorResponseType(typeof(ResponseDto<object>))]

Tooark attributes in MVC validation

  • TooarkDependencyInjection.AddTooarkValidationAttributes(IServiceCollection): makes MVC stop inferring [Required] on members validated by a Tooark.Attributes attribute.

With <Nullable>enable</Nullable>, MVC treats every non-nullable reference type as if it had [Required], with the framework's message (The Email field is required.), which is not a translation key. The Tooark.Attributes attributes already report the missing value with the Field.Required key, so, without the registration, a missing field gets both messages. With the registration, only the attribute's key remains:

Missing member Without the registration With the registration
[EmailValidation] string Email The Email field is required. and Field.Required;Email Field.Required;Email
string Name, without a Tooark attribute The Name field is required. The Name field is required.
[Required][EmailValidation] string Email both messages both messages

The reach is that of the Tooark attributes. The inferred [Required] only leaves a member that has a Tooark attribute. A [Required] declared on the member stays, because it is the choice of whoever wrote the DTO, and members without a Tooark attribute keep the inference. That is the difference from SuppressImplicitRequiredAttributeForNonNullableReferenceTypes, which turns the inference off for every DTO in the application. The member is still flagged as required in the MVC metadata, which is true: the attribute rejects the missing value.

Registration order does not matter. The provider that infers [Required] enters the MVC options with AddControllers. The registration is applied after every configuration (PostConfigure), so it runs after that provider, whether called before or after AddControllers. Calling it twice does not repeat the registration.

Where it applies. In MVC validation: positional record, class and action parameter, in controllers with or without [ApiController] and with or without the envelope. Minimal APIs do not go through the MVC options.

The envelope does not turn it on. AddTooarkModelStateEnvelope and this registration are independent, and neither calls the other: this one chooses the messages of a missing field, and the envelope, the body in which they reach the client.

Problem Details for exceptions

  • TooarkDependencyInjection.AddTooarkProblemDetails(IServiceCollection, Action<ProblemDetailsOptions>?): makes the Tooark.Exceptions exceptions answer with Problem Details (RFC 9457), in the status each exception defines, in controllers and minimal APIs.
  • TooarkExceptionHandler: the IExceptionHandler the registration adds. It can be registered on its own with AddExceptionHandler<TooarkExceptionHandler>(), next to AddProblemDetails().
  • ProblemDetailsError: an item of the errors list of the body, with code, key and message.
  • TooarkProblemDetailsOptions: the log level of each handled exception and the conversion of the ASP.NET Core validation failures to the errors list.

Without it, a NotFoundException thrown in an endpoint is an exception like any other: ASP.NET Core answers 500, and the status and the message the exception carries are lost. The registration adds the AddProblemDetails of ASP.NET Core and an IExceptionHandler that recognizes the TooarkException family: the status comes from GetStatusCode() and the body from GetNotifications(), with the messages translated in the language of the request by the IStringLocalizer registered in the container or, when none is registered, by the Tooark.Extensions localizer.

GET /users/1 throwing new NotFoundException("NotFound.User"), in en-US:

HTTP/1.1 404 Not Found
Content-Type: application/problem+json
{
  "type": "https://tools.ietf.org/html/rfc9110#section-15.5.5",
  "title": "Not Found",
  "status": 404,
  "detail": "User not found",
  "instance": "/users/1",
  "errors": [
    { "code": "T.ERR", "key": "Unknown", "message": "User not found" }
  ],
  "traceId": "0HNPTVUT6D34Q"
}
Member Source
status TooarkException.GetStatusCode()
title The standard reason phrase of the status (Not Found, Bad Request)
type The RFC 9110 section of the status, applied by ASP.NET Core
detail The first message of errors
instance The request path
errors One item per NotificationItem of the exception: code and key as recorded, message translated
traceId Added by ASP.NET Core

An exception built from a Notification carries one item per failure, with the code and the key of each validation; one built from a message carries a single item with the defaults T.ERR and Unknown. A message that is not a translation key, such as "User.NotFound", arrives as written.

Which exceptions. Every class of Tooark.Exceptions, in its status: BadRequestException 400, UnauthorizedException 401, ForbiddenException 403, NotFoundException 404, ConflictException 409, UnprocessableEntityException 422, TooManyRequestsException 429, InternalServerErrorException 500 and the others of the package. Any other exception is left to ASP.NET Core, which answers the default 500 Problem Details of AddProblemDetails, without the exception's message: a bug does not leak its text to the client.

Where it applies. Wherever the exception reaches the UseExceptionHandler middleware: minimal API handlers, controller actions and filters, and the middlewares after it. The middleware has to be in the pipeline, without arguments and before the middlewares that may throw. AddProblemDetails is what lets UseExceptionHandler be called without an error path:

builder.Services.AddTooarkProblemDetails();

var app = builder.Build();

app.UseExceptionHandler();   // no arguments: the Problem Details service is the fallback
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();

Writing the body. The body is written by the IProblemDetailsService of ASP.NET Core, so the CustomizeProblemDetails of the application applies to it and type gets the default of the status. When the service refuses to write β€” a client that sent an Accept without JSON, for instance β€” the handler writes the body itself, in application/problem+json: an exception of the Tooark family never ends in a 500 without a body. The configure parameter is the ProblemDetailsOptions of ASP.NET Core:

builder.Services.AddTooarkProblemDetails(options =>
  options.CustomizeProblemDetails = context =>
    context.ProblemDetails.Extensions["application"] = "orders-api");

Independent of the envelope. AddTooarkModelStateEnvelope shapes the validation failure of [ApiController] controllers, which happens before the action, with ResponseDto. This registration shapes the exceptions, which happen during the action, and neither changes the other. An API can use both, or choose Problem Details for everything by not registering the envelope: without it, the validation failure also comes out in the Tooark errors list (see below). Calling the registration twice does not repeat the handler.

Logging. The handled exception is logged in the Tooark.AspNetCore.ExceptionHandling.TooarkExceptionHandler category: Information for a 4xx status, with the status and the message, and Error for a 5xx, with the exception and its stack trace. On .NET 10 UseExceptionHandler does not log an exception that an IExceptionHandler handled, so this is the only entry. A 404 or a 409 is part of normal operation; to change the level, per range or per status, configure TooarkProblemDetailsOptions:

builder.Services.Configure<TooarkProblemDetailsOptions>(options =>
{
  options.ClientErrorLogLevel = LogLevel.Information;                // 4xx (default)
  options.ServerErrorLogLevel = LogLevel.Error;                      // 5xx (default)
  options.StatusCodeLogLevels[StatusCodes.Status401Unauthorized] = LogLevel.Warning;
  options.StatusCodeLogLevels[StatusCodes.Status404NotFound] = LogLevel.Debug;
});

Options. TooarkProblemDetailsOptions is code only, through services.Configure<TooarkProblemDetailsOptions> before or after AddTooarkProblemDetails: there is no configuration section for it. It is read from the request container on each response. The table gives the Tooark default and what each option is for; below it, the practical effect.

Property Type Default What it is for
ClientErrorLogLevel LogLevel Information Log level of a Tooark exception answered with a 4xx
ServerErrorLogLevel LogLevel Error Log level of a Tooark exception answered with a 5xx
StatusCodeLogLevels IDictionary<int, LogLevel> {} Log level per status, which wins over the level of its range
ConvertValidationProblems bool true Answers the ASP.NET Core validation failures in the Tooark list
  • ClientErrorLogLevel: the log entry of a 4xx carries the status and the message, without the exception. The level goes through the filters of the Logging section: with Information and "Default": "Warning" in production, 4xx entries are not written unless the Tooark.AspNetCore.ExceptionHandling.TooarkExceptionHandler category is allowed.
  • ServerErrorLogLevel: the log entry of a 5xx carries the exception, with its stack trace, whatever the level. Since this is the only entry for the exception, LogLevel.None leaves 5xx responses with no log at all.
  • StatusCodeLogLevels: the dictionary is read-only as a property; add the entries to it, as in the example above. LogLevel.None leaves the status out of the log.
  • ConvertValidationProblems: with true, the ASP.NET Core validation failures come out in the Tooark errors list (see validation failures, below); with false, they come out in the ASP.NET Core format, with errors per field. The conversion is registered by AddTooarkProblemDetails: with TooarkExceptionHandler registered on its own, nothing is converted.

The levels apply only to the Tooark exceptions answered by the handler: the TooarkResults results and the other exceptions do not go through them. On 4.x, where the options appeared (v4.10.0), the 4xx default was Warning.

GetLogLevel(int statusCode) returns the level a status resolves to, by the same rule the handler applies: the level of the status when it is in StatusCodeLogLevels; otherwise ServerErrorLogLevel from 500 up and ClientErrorLogLevel for the rest. It is public since v4.11.0 and is useful to check the configuration in a test, without capturing the log. With the configuration above:

// factory: the WebApplicationFactory<Program> of the test
var options = factory.Services.GetRequiredService<IOptions<TooarkProblemDetailsOptions>>().Value;

Assert.Equal(LogLevel.Debug, options.GetLogLevel(StatusCodes.Status404NotFound));          // level of the status
Assert.Equal(LogLevel.Information, options.GetLogLevel(StatusCodes.Status409Conflict));    // level of the 4xx range
Assert.Equal(LogLevel.Error, options.GetLogLevel(StatusCodes.Status500InternalServerError));

Validation failures in the Tooark format. The ASP.NET Core ValidationProblemDetails carries errors as an object with the messages per field, and the Tooark Problem Details carries errors as the list of code, key and message. So that a client receives a single format, the ASP.NET Core validation failures also come out in the Tooark list, one entry per message, with the field in key, the default code T.ERR and the translated message: a key such as Field.Required;Email arrives translated, and the framework text arrives as the framework writes it. status, type, traceId and the extensions of CustomizeProblemDetails stay in the body, and title becomes the standard reason phrase of the status, as for the exceptions. CustomizeProblemDetails runs before the conversion, on the ASP.NET Core problem: a title or a detail set there is replaced.

// ASP.NET Core format
{ "status": 400, "title": "One or more validation errors occurred.", "errors": { "Email": ["The Email field is required."] } }

// As it comes out with AddTooarkProblemDetails
{ "status": 400, "title": "Bad Request", "detail": "The Email field is required.", "errors": [{ "code": "T.ERR", "key": "Email", "message": "The Email field is required." }] }
Source of the failure Converted
Automatic validation of [ApiController] Yes
Automatic validation of [ApiController] with the envelope No: the envelope answers with ResponseDto
ValidationProblem() of a controller Yes
Minimal API validation (AddValidation) Yes
Results.ValidationProblem and TypedResults.ValidationProblem Yes

The conversion is on since v5; on 4.x it appeared off, in v4.10.0. To keep the ASP.NET Core format, turn it off:

builder.Services.Configure<TooarkProblemDetailsOptions>(options => options.ConvertValidationProblems = false);

To convert by hand, in both directions, see conversion between the formats.

OpenAPI. ProblemDetails is already the error type ASP.NET Core assumes for [ApiController], so a [ProducesResponseType(StatusCodes.Status404NotFound)] documents the response; in minimal APIs, .ProducesProblem(StatusCodes.Status404NotFound) does the same. The errors extension is not described by the framework. With the validation failure conversion, which is on by default, document the validation failure as ProblemDetails (.ProducesProblem(StatusCodes.Status400BadRequest), or [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)] in controllers), not with .ProducesValidationProblem(): the HttpValidationProblemDetails schema describes errors as an object per field.

Results for minimal APIs

  • TooarkResults.Problem(TooarkException): answers an exception without throwing it, with the body the handler writes. When the result runs, the messages are translated by the application's IStringLocalizer, when it registers one, as in the handler, and otherwise by the Tooark.Extensions localizer, which also translates the value read before the result runs (IValueHttpResult).
  • TooarkResults.ValidationProblem(Notification, int statusCode = 400): answers the notifications of an entity or a value object, 400 by default.
  • TooarkResults.ValidationProblem(IEnumerable<NotificationItem>, int statusCode = 400): the same, from a list of items.

Minimal APIs have no ModelState. The Tooark.Entities entities and the Tooark.ValueObjects value objects validate themselves and accumulate notifications, and the endpoint returns the problem when IsValid is false, with one item in errors per notification. The result fills instance with the request path when it runs, and the status must be an error status, from 400 to 599. A valid notification produces a problem with an empty errors list: check IsValid before calling it.

The results do not depend on AddTooarkProblemDetails: they translate the messages with the Tooark.Extensions localizer by themselves, in the language of the request.

Conversion between the validation formats

  • ValidationProblemExtension.ToNotificationItems(IDictionary<string, string[]>): converts the ASP.NET Core messages per field into Tooark notification items, one per message, with the field as the key and the default code T.ERR.
  • ValidationProblemExtension.ToNotificationItems(HttpValidationProblemDetails): the same, from the validation problem.
  • ValidationProblemExtension.ToValidationErrors(IEnumerable<NotificationItem>): the way back, with the items grouped by key and the messages translated. The code of each item is lost: the ASP.NET Core format has nowhere to keep it.

The conversion is explicit, not an implicit operator: a field with several messages becomes several items, and the way back loses the code, which an implicit conversion would hide. The framework would also never call an operator when writing the response; that is what ConvertValidationProblems is for. A blank message becomes Field.Invalid;{field}, or BadRequest without a field, as in GetErrors.

using Tooark.AspNetCore.Extensions;
using Tooark.AspNetCore.Results;

// From the ASP.NET Core format to the Tooark list
var items = problem.ToNotificationItems();
return TooarkResults.ValidationProblem(items);

// From the Tooark list to the ASP.NET Core format (with the conversion off)
return Results.ValidationProblem(order.Notifications.ToValidationErrors());

Since v4.11.0 the converted items can also be thrown as an exception. NotificationList, from Tooark.Notifications, builds a notification from existing items, and every Tooark exception accepts a notification and keeps the key and the code of each item. With AddTooarkProblemDetails, each item reaches the errors list of the response:

using Tooark.AspNetCore.Extensions;
using Tooark.Exceptions;
using Tooark.Notifications;

// errors: IDictionary<string, string[]>, the ASP.NET Core validation format
throw new BadRequestException(new NotificationList(errors.ToNotificationItems()));

Integration with the validations

The returned messages are what the Tooark.Attributes attributes produce: translation keys in the Key;Field format, such as Field.Required;Email. They become text through the IStringLocalizer of Tooark.Extensions, which resolves the language from the request's execution flow.

Errors generated by model binding itself β€” an integer receiving text, for instance β€” come with the framework's message, not with a key. The localizer returns that text unchanged and flags ResourceNotFound, which lets you tell the two cases apart when it matters.

A missing non-nullable field may carry both messages: the attribute's Field.Required key and the [Required] that MVC infers, with the framework's text. AddTooarkValidationAttributes keeps only the key: see Tooark attributes in MVC validation.

Uploaded files

  • FormFileExtension.ToMemoryStream(IFormFile?, long maxBytes = 0): copies the binary content of the file to a MemoryStream, with a size limit.
  • FormFileExtension.ToMemoryStreamAsync(IFormFile?, long maxBytes = 0, CancellationToken cancellationToken = default): the same, asynchronously.
  • FormFileExtension.GetExtension(IFormFile?): returns the extension of the file name, in uppercase and without the dot.
  • FormFileExtension.IsImage(IFormFile?, long maxBytes = 0): checks whether the file is a valid image, by the extension of the name and by the size.
  • FormFileExtension.IsDocument(IFormFile?, long maxBytes = 0): the same, for a document.
  • FormFileExtension.IsVideo(IFormFile?, long maxBytes = 0): the same, for a video.
  • FormFileExtension.IsCustom(IFormFile?, long maxBytes = 0, string[]? permittedExtensions = null): the same, for the given extensions.
  • FormFileExtension.IsImageContent(IFormFile?, long maxBytes = 0): checks the name, the size and the content: the real format, recognized by the bytes, must be an image, and the extension of the name one of that format.
  • FormFileExtension.IsDocumentContent(IFormFile?, long maxBytes = 0): the same, for a document.
  • FormFileExtension.IsVideoContent(IFormFile?, long maxBytes = 0): the same, for a video.
  • FormFileExtension.IsCustomContent(IFormFile?, IReadOnlyCollection<EFileFormat> permittedFormats, long maxBytes = 0): the same, for the given formats.

They are extension methods on IFormFile, in the Tooark.AspNetCore.Files namespace. The *Content ones exist since v5.0.0, and the others since v4.11.0. They apply the rules of FileConvert and FileValid from Tooark.Utils: the same size limit, the same extensions and the same exception. They live in this package because IFormFile is an ASP.NET Core type.

using Tooark.AspNetCore.Files;
using Tooark.Exceptions;

if (!file.IsImage(maxBytes: 2 * 1024 * 1024))
{
  throw new BadRequestException("File.InvalidImage");
}

await using var content = await file.ToMemoryStreamAsync(2 * 1024 * 1024, cancellationToken);

Conversion. ToMemoryStream and ToMemoryStreamAsync return null for a null or empty file. Above maxBytes they throw a PayloadTooLargeException (HTTP 413), with the message File.SizeExceeded;{limit}. A non-positive value applies FileConvert.DefaultMaxBytes, 5242880 bytes (5MB), and the absolute ceiling is int.MaxValue. The declared size is refused before the file is opened, and the limit is checked again while reading, so it holds even when the declared size does not match the content. The returned MemoryStream is already positioned at the start.

Extension. GetExtension reads the file name, which is given by whoever sends the file. Only ASCII letters and digits pass, with at most ten characters; anything else, and a null file, result in null.

Validation. IsImage, IsDocument, IsVideo and IsCustom check the size and the extension declared in the file name. The content is not inspected, so they do not replace checking the actual file type when the upload is untrusted: for that, use the *Content versions below. A null or empty file, or one above maxBytes, results in false, without an exception, and a non-positive value applies the 5MB default.

Method Accepted extensions
IsImage .JPG, .JPEG, .PNG, .GIF, .BMP and .WEBP
IsDocument .TXT, .CSV, .LOG, .PDF, .DOC, .DOCX, .XLS, .XLSX, .PPT and .PPTX
IsVideo .AVI, .MP4, .MPG, .MPEG and .WMV
IsCustom Those in permittedExtensions; null or empty applies every image, document and video one

The IsCustom extensions are compared case-insensitively and may be given with or without the leading dot: "pdf" and ".PDF" have the same effect. .SVG is not in the image list since v5, because it can carry script; to accept it, pass the list to IsCustom, with .svg and the other extensions.

Validation by content. IsImageContent, IsDocumentContent and IsVideoContent apply the name and size rules of IsImage, IsDocument and IsVideo, and then read the start of the content to recognize the real format by its signature. The format must be one of the category (image: JPEG, PNG, GIF, BMP, WebP; document: PDF, ZIP, Compound File, plain text; video: AVI, MP4, MPEG, ASF), and the extension of the name one of that format: a PNG named photo.jpg, an SVG named photo.png and an HTML named notes.txt are refused. They are the Stream versions of FileValid over the uploaded content, which is opened and closed again. The signature confirms the container, not the document: any ZIP named sheet.xlsx passes.

IsCustomContent takes the formats (EFileFormat, in Tooark.Utils.Enums), not extensions, and has no category list of extensions: it checks the size, that the real format is in the list and that the extension of the name is one of that format. With [EFileFormat.Heic, EFileFormat.Avif], an iPhone photo named IMG_0001.HEIC passes, and a JPEG with the same name does not. An empty list refuses every file, EFileFormat.Unknown in the list has no effect, and a null list throws ArgumentNullException.

using Tooark.AspNetCore.Files;
using Tooark.Exceptions;
using Tooark.Utils.Enums;

if (!file.IsImageContent(maxBytes: 2 * 1024 * 1024))
{
  throw new BadRequestException("File.InvalidImage");
}

var accepted = file.IsCustomContent([EFileFormat.Heic, EFileFormat.Avif, EFileFormat.Jpeg]);

Migration from Tooark.Utils. The Tooark.Utils methods that took an IFormFile were removed in v5, together with its dependency on the Microsoft.AspNetCore.Http 2.x package; they were obsolete since v4.11.0. Each one has an extension here, with the same rules:

Removed (Tooark.Utils) Extension (Tooark.AspNetCore.Files)
FileConvert.ToMemoryStream(file) file.ToMemoryStream()
FileConvert.ToMemoryStreamAsync(file) file.ToMemoryStreamAsync()
FileConvert.Extension(file) file.GetExtension()
FileValid.IsImage(file) file.IsImage()
FileValid.IsDocument(file) file.IsDocument()
FileValid.IsVideo(file) file.IsVideo()
FileValid.IsCustom(file) file.IsCustom()

The optional parameters stay in the same order. In the validation methods, the maximum size was called fileSize and is now called maxBytes: whoever passes it by name has to rename it. For a file that does not arrive as an IFormFile, Tooark.Utils has the versions that take a Stream and a file name.

Tenant resolution

AddTooarkTenant and UseTooarkTenant resolve the tenant of each request from the signed-in user, once, and keep it in a scoped TenantContext, which is the ITenantProvider (from Tooark.Entities) of the request. The context of Tooark.Entities.EntityFrameworkCore reads it to filter the queries and to fill and check the tenant of the writes.

using Tooark.AspNetCore.Injections;
using Tooark.AspNetCore.Middlewares;

builder.Services.AddTooarkTenant();

var app = builder.Build();

app.UseAuthentication();
app.UseTooarkTenant();   // after the authentication, before the authorization and the endpoints
app.UseAuthorization();

How a request gets its tenant:

  1. A request without an authenticated identity has no tenant, and the resolver is not called.
  2. The middleware reads the claim named in TooarkTenantOptions.ClaimType (default tid, the tenant of Microsoft Entra ID) from the authenticated identities. Without the claim, or with different values of it, there is no tenant.
  3. The value β€” the external tenant id, as text β€” goes to the ITenantResolver, which returns the internal Guid of the tenant, or null. The default GuidTenantResolver accepts the value when it is a GUID, with or without hyphens, braces or parentheses (Guid.TryParse); any other value, and Guid.Empty, means no tenant.
  4. The result goes to the TenantContext of the request scope. The resolver runs once per request, however many times the tenant is read.

Without a tenant, the queries on the tenant entities return nothing and adding a tenant entity fails (fail closed). The middleware does not answer 401 or 403: whether a route requires a tenant is up to the authorization of the application.

Option Type Default What it is for
ClaimType string tid Claim with the external tenant id (tid in Entra, org_id in Auth0)

The options are set in code only, through the Action<TooarkTenantOptions> of AddTooarkTenant: the claim depends on the identity provider that the application integrates in code, not on the environment, so there is no configuration section. An empty or whitespace ClaimType fails at registration, in AddTooarkTenant itself, with an InternalServerErrorException carrying Options.Tenant.ClaimTypeRequired.

Claim mapping. With MapInboundClaims on in AddJwtBearer or AddOpenIdConnect of ASP.NET Core, the handler renames tid to http://schemas.microsoft.com/identity/claims/tenantid. Set ClaimType to that name, or turn the mapping off. AddTooarkJwtBearer and the providers of Tooark.Securities.OpenId already keep it off.

Mapping an external identifier

When the identifier of the identity provider is not the internal tenant id β€” an Auth0 organization org_abc123, or an Entra tid that the application keeps next to its own tenant id β€” implement ITenantResolver and register it with AddTooarkTenant<TResolver>:

using Microsoft.EntityFrameworkCore;
using Tooark.AspNetCore.Tenancy;

public sealed class OrganizationTenantResolver(AppDbContext context) : ITenantResolver
{
  public async ValueTask<Guid?> ResolveAsync(string externalTenantId, CancellationToken cancellationToken = default) =>
    await context.Tenants
      .Where(tenant => tenant.OrganizationId == externalTenantId)   // "org_abc123"
      .Select(tenant => (Guid?)tenant.Id)
      .SingleOrDefaultAsync(cancellationToken);
}
builder.Services.AddTooarkTenant<OrganizationTenantResolver>(options => options.ClaimType = "org_id");

The resolver is scoped and can depend on the application's DbContext: the tenant table does not implement ITenantEntity, so it is not filtered. Keep a cache inside the resolver when the lookup has a cost: with Tooark.Caching, in the Shared scope, because the resolver runs before the request has a tenant. It returns only the identifier: the settings of each tenant stay in the application.

Registration
Call What it registers
AddTooarkTenant(configure) The options, TenantContext (scoped), ITenantProvider as that same instance and GuidTenantResolver as ITenantResolver
AddTooarkTenant<TResolver>(configure) Same, with TResolver (scoped) as ITenantResolver
UseTooarkTenant() The middleware. Without AddTooarkTenant, it fails at startup with Tenant.ResolutionNotRegistered

The services are added only when the application has not registered its own: an ITenantProvider registered before prevails, and the resolved tenant stays only in TenantContext.

Outside a request

A hosted service has no request and therefore no tenant. To work for one tenant, it creates a scope and sets the tenant before using the context:

await using var scope = scopeFactory.CreateAsyncScope();

scope.ServiceProvider.GetRequiredService<TenantContext>().SetTenantId(tenantId);

TenantContext is scoped, so a pooled DbContext cannot receive it in its constructor: a scoped factory passes the tenant to the context on each lease, as the README of Tooark.Entities.EntityFrameworkCore shows.

Filters and middlewares

The first middleware is the tenant resolution, under the Middlewares/ folder: the tenant has to be resolved before the endpoint, and asynchronously, which only a middleware does. The validation response is not a filter: ASP.NET Core already calls a factory at the point where it decides the body of a validation failure, and replacing that factory was enough. The exception handling is not a middleware either: ASP.NET Core has the IExceptionHandler contract, which the UseExceptionHandler middleware already calls, and implementing it was enough. New filters and middlewares go in this package, under the Filters/ and Middlewares/ folders. The family only splits a package when the dependency profile differs β€” that is what motivated separating Tooark.Mediator.EntityFrameworkCore, which pulls Entity Framework Core, from Tooark.Mediator, which does not use it. Filters, middlewares and the extensions here share exactly the same profile, so splitting them into separate packages would reduce nothing.

Namespaces

The ModelState and validation extensions live in Tooark.AspNetCore.Extensions, the IFormFile ones in Tooark.AspNetCore.Files, the registrations in Tooark.AspNetCore.Injections, the exception handler and its options in Tooark.AspNetCore.ExceptionHandling, the minimal API results in Tooark.AspNetCore.Results, the tenant types (TooarkTenantOptions, ITenantResolver, GuidTenantResolver, TenantContext) in Tooark.AspNetCore.Tenancy and UseTooarkTenant in Tooark.AspNetCore.Middlewares.


πŸ“ Usage Examples

Standard response for validation failures

using Tooark.AspNetCore.Injections;

builder.Services.AddControllers();
builder.Services.AddTooarkModelStateEnvelope();

The DTO validated by the Tooark.Attributes attributes:

using Tooark.Attributes;

public sealed class CreatePersonDto
{
  [EmailValidation]
  public string Email { get; set; } = null!;

  [DocumentValidation("CPF")]
  public string Cpf { get; set; } = null!;
}
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("people")]
public sealed class PersonController : ControllerBase
{
  [HttpPost]
  public IActionResult Create([FromBody] CreatePersonDto dto)
  {
    // Only reached with a valid ModelState: [ApiController] answers 400 before the action runs
    return Ok();
  }
}

POST /people with {"email": "x", "cpf": "123"}, in en-US:

{
  "data": null,
  "errors": ["Field Document is invalid", "Field Email is invalid"],
  "pagination": null,
  "metadata": []
}

A model binding failure β€” text in a numeric field, an empty body β€” comes in the same body, with the framework's message in errors.

With only the envelope registered, a missing field carries two messages: without email in the body, errors gets "Field Email is required" and also "The Email field is required.", the [Required] that MVC infers. The next example adds AddTooarkValidationAttributes, which keeps only the first.

The name that appears in the message is the attribute's, not the property's: that is why the Cpf field produces Field.Invalid;Document, the default of DocumentValidationAttribute. To align the two, pass the propertyName:

[DocumentValidation("CPF", propertyName: "Cpf")]
public string Cpf { get; set; } = null!;

Missing field without the framework's message

using Tooark.AspNetCore.Injections;

builder.Services.AddControllers();
builder.Services.AddTooarkModelStateEnvelope();
builder.Services.AddTooarkValidationAttributes();

A positional record, with the attribute on the constructor parameter:

using Tooark.Attributes;

public sealed record CreateContactDto([EmailValidation] string Email, string Name);

POST /contacts with {"name": "Ana"}, in en-US:

{
  "data": null,
  "errors": ["Field Email is required"],
  "pagination": null,
  "metadata": []
}

Without AddTooarkValidationAttributes, errors would also carry "The Email field is required.". With {"email": "ana@test.com"}, the missing Name answers "The Name field is required.": the field has no Tooark attribute, and the MVC inference still applies to it.

Reading the ModelState errors in the action

Without [ApiController], ASP.NET Core does not check the ModelState before the action, and the action does it. In a controller with the attribute this check never runs: the framework answers 400 first.

using Microsoft.AspNetCore.Mvc;
using Tooark.AspNetCore.Extensions;

[Route("people")]
public sealed class PersonController : ControllerBase
{
  [HttpPost]
  public IActionResult Create([FromBody] CreatePersonDto dto)
  {
    if (!ModelState.IsValid)
    {
      // ["Field.Invalid;Document", "Field.Invalid;Email"]
      var errors = ModelState.GetErrors();

      return BadRequest(errors);
    }

    return Ok();
  }
}

With translated messages

The keys become text through the IStringLocalizer, which comes from Tooark.Extensions and is registered there:

using Tooark.Extensions.Injections;

builder.Services.AddTooarkExtensions();
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Localization;
using Tooark.AspNetCore.Extensions;

[Route("people")]
public sealed class PersonController(IStringLocalizer localizer) : ControllerBase
{
  [HttpPost]
  public IActionResult Create([FromBody] CreatePersonDto dto)
  {
    if (!ModelState.IsValid)
    {
      // ["Field Document is invalid", "Field Email is invalid"]
      var errors = ModelState.GetErrors().Select(error => localizer[error].Value);

      return BadRequest(errors);
    }

    return Ok();
  }
}

A filter for controllers without [ApiController]

The same check in every endpoint calls for a filter. The package does not ship one, because in [ApiController] controllers the validation response already does the job. For controllers without the attribute it fits in a few lines, and with ResponseDto it answers with the same body:

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Tooark.AspNetCore.Extensions;
using Tooark.Dtos;

public sealed class ValidationFilter : IActionFilter
{
  public void OnActionExecuting(ActionExecutingContext context)
  {
    if (!context.ModelState.IsValid)
    {
      context.Result = new BadRequestObjectResult(new ResponseDto<object>(context.ModelState.GetErrors()));
    }
  }

  public void OnActionExecuted(ActionExecutedContext context) { }
}
builder.Services.AddControllers(options => options.Filters.Add<ValidationFilter>());

Problem Details for the Tooark exceptions

using Tooark.AspNetCore.Injections;
using Tooark.Exceptions;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddTooarkProblemDetails();

var app = builder.Build();
app.UseExceptionHandler();

app.MapGet("/users/{id:guid}", async (Guid id, IUserRepository users) =>
  await users.FindAsync(id) ?? throw new NotFoundException("NotFound.User"));

app.Run();

GET /users/3fa85f64-5717-4562-b3fc-2c963f66afa6, in en-US, for a user that does not exist:

{
  "type": "https://tools.ietf.org/html/rfc9110#section-15.5.5",
  "title": "Not Found",
  "status": 404,
  "detail": "User not found",
  "instance": "/users/3fa85f64-5717-4562-b3fc-2c963f66afa6",
  "errors": [
    { "code": "T.ERR", "key": "Unknown", "message": "User not found" }
  ],
  "traceId": "0HNPTVUT6D34Q"
}

NotFound.User is a key of the Tooark.Extensions resources, so it arrives translated. A message that is not a key, such as "User.NotFound", arrives as written.

An exception built from a notification carries one item per failure, with the code and the key of each validation:

using Tooark.Exceptions;
using Tooark.ValueObjects;

app.MapPut("/users/{id:guid}/email", (Guid id, ChangeEmailRequest request) =>
{
  var email = new Email(request.Email);

  if (!email.IsValid)
  {
    // 400 with errors: [{ "code": "T.VLD.RGX1", "key": "Email", "message": "Field Email is invalid" }]
    throw new BadRequestException(email);
  }

  // ...
  return Results.NoContent();
});

Validation of an entity in a minimal API

Without an exception, returning the notifications of the entity:

using Tooark.AspNetCore.Results;

app.MapPost("/users", (CreateUserRequest request) =>
{
  var user = new User(request.Name, request.Email);

  return user.IsValid
    ? Results.Created($"/users/{user.Id}", user)
    : TooarkResults.ValidationProblem(user);
});

POST /users with an invalid e-mail, in pt-BR:

{
  "type": "https://tools.ietf.org/html/rfc9110#section-15.5.1",
  "title": "Bad Request",
  "status": 400,
  "detail": "O campo E-mail Γ© invΓ‘lido",
  "instance": "/users",
  "errors": [
    {
      "code": "T.VLD.RGX1",
      "key": "Email",
      "message": "O campo E-mail Γ© invΓ‘lido"
    }
  ],
  "traceId": "0HNPTVUT6D34Q"
}

For a 422 instead of a 400, pass the status: TooarkResults.ValidationProblem(user, StatusCodes.Status422UnprocessableEntity). To answer an exception without throwing it β€” a result the caller already has in hand β€” use TooarkResults.Problem(new ConflictException("Record.Exists")).

Problem Details in a controller

using Microsoft.AspNetCore.Mvc;
using Tooark.Exceptions;

[ApiController]
[Route("users")]
public sealed class UsersController(IUserRepository users) : ControllerBase
{
  [HttpGet("{id:guid}")]
  [ProducesResponseType(StatusCodes.Status200OK)]
  [ProducesResponseType(StatusCodes.Status404NotFound)]
  public async Task<IActionResult> Get(Guid id)
  {
    var user = await users.FindAsync(id) ?? throw new NotFoundException("NotFound.User");

    return Ok(user);
  }
}

The same AddTooarkProblemDetails and UseExceptionHandler serve the controller: the exception leaves the action, crosses the MVC filters and reaches the middleware. The envelope, when registered, keeps answering the validation of the [ApiController], which happens before the action.

File upload in a controller

using Microsoft.AspNetCore.Mvc;
using Tooark.AspNetCore.Files;
using Tooark.Exceptions;

[ApiController]
[Route("users")]
public sealed class PhotosController(IPhotoRepository photos) : ControllerBase
{
  private const long MaxSize = 2 * 1024 * 1024; // 2MB

  [HttpPut("{id:guid}/photo")]
  public async Task<IActionResult> Upload(Guid id, IFormFile file, CancellationToken cancellationToken)
  {
    // Image extension and up to 2MB; the content is not inspected
    if (!file.IsImage(MaxSize))
    {
      throw new BadRequestException("File.InvalidImage");
    }

    // After IsImage the file has content and an extension, so neither is null
    await using var content = await file.ToMemoryStreamAsync(MaxSize, cancellationToken);
    var extension = file.GetExtension(); // PNG, for example

    await photos.SaveAsync(id, content!, extension!, cancellationToken);

    return NoContent();
  }
}

IsImage returns false for a file above the limit, and the action throws the BadRequestException. ToMemoryStreamAsync checks the same limit while reading and, if the actual content goes beyond it, throws the PayloadTooLargeException. With AddTooarkProblemDetails, both exceptions come out as Problem Details, in the status of each: 400 and 413.

Tenant of each request with Entity Framework Core

The entity implements ITenantEntity and the context implements ITenantDbContext, as in the complete example of Tooark.Entities.EntityFrameworkCore. The API resolves the tenant from the tid claim of Microsoft Entra ID:

using Microsoft.EntityFrameworkCore;
using Tooark.AspNetCore.Injections;
using Tooark.AspNetCore.Middlewares;
using Tooark.Entities.EntityFrameworkCore.Extensions;
using Tooark.Entities.EntityFrameworkCore.Injections;

builder.Services.AddHttpContextAccessor();
builder.Services.AddTooarkTenant();
builder.Services.AddTooarkEntityFrameworkCore<HttpContextCurrentUser>();
builder.Services.AddDbContext<AppDbContext>((sp, options) => options
  .UseNpgsql(connectionString)
  .AddTooarkInterceptors(sp));

var app = builder.Build();

app.UseAuthentication();
app.UseTooarkTenant();
app.UseAuthorization();

// The endpoint does not deal with the tenant: the query sees only the current tenant, and the new project receives it
app.MapGet("/projects", (AppDbContext db, CancellationToken ct) => db.Projects.ToListAsync(ct)).RequireAuthorization();
app.MapPost("/projects", async (CreateProject request, AppDbContext db, CancellationToken ct) =>
{
  db.Projects.Add(new Project(request.Name));
  await db.SaveChangesAsync(ct);

  return Results.NoContent();
}).RequireAuthorization();

With Auth0 organizations, only the registration changes:

builder.Services.AddTooarkTenant<OrganizationTenantResolver>(options => options.ClaimType = "org_id");

πŸ“‹ Dependencies

Package Version Description
Tooark.Attributes 5.x The attributes recognized by AddTooarkValidationAttributes
Tooark.Dtos 5.x ResponseDto, the body of the validation response
Tooark.Entities 5.x ITenantProvider, implemented by TenantContext
Tooark.Exceptions 5.x The exceptions answered with Problem Details, and their notification items
Tooark.Extensions 5.x Error message localization
Microsoft.AspNetCore.App (shared framework) 10.x ModelStateDictionary, ApiBehaviorOptions, MvcOptions, IExceptionHandler, IProblemDetailsService and IFormFile

🀝 Contributing

Contributions are welcome! Start with CONTRIBUTING.md β€” it covers the development workflow, the coding and commit conventions and the pull request checklist. Bugs and feature requests go through the issue templates of the Tooark repository.

By participating you agree to the Code of Conduct.


πŸ†˜ Help & Security

  • ❓ Questions, bugs, feature ideas β€” see SUPPORT.md for the right channel
  • πŸ”’ Security vulnerabilities β€” do not open a public issue; follow SECURITY.md

πŸ’– Support

If Tooark helps your projects, consider supporting its development:

Every contribution helps keep the project maintained and improving. Thank you! πŸ™


πŸ“„ License

This project is licensed under the BSD 3-Clause License.

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (1)

Showing the top 1 NuGet packages that depend on Tooark.AspNetCore:

Package Downloads
Tooark

Package with all Tooark resources for .NET applications.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
5.0.0 69 12/1/2026
4.12.2 64 12/1/2026
4.12.1 72 11/30/2026
4.12.0 122 11/29/2026
4.11.0 222 11/21/2026
4.10.0 154 11/18/2026
4.9.0 144 11/16/2026
4.8.0 176 11/15/2026
4.7.3 139 11/11/2026
4.7.2 116 11/3/2026
4.7.1 158 10/17/2026
4.7.0 179 9/30/2026
4.6.0 175 9/29/2026
4.5.0 134 9/29/2026
4.4.0 138 9/28/2026
4.3.0 137 9/26/2026
4.2.1 140 9/25/2026
4.2.0 157 9/20/2026
4.1.0 130 9/18/2026
4.0.1 155 8/25/2026
Loading failed