Tooark.AspNetCore
4.11.0
dotnet add package Tooark.AspNetCore --version 4.11.0
NuGet\Install-Package Tooark.AspNetCore -Version 4.11.0
<PackageReference Include="Tooark.AspNetCore" Version="4.11.0" />
<PackageVersion Include="Tooark.AspNetCore" Version="4.11.0" />
<PackageReference Include="Tooark.AspNetCore" />
paket add Tooark.AspNetCore --version 4.11.0
#r "nuget: Tooark.AspNetCore, 4.11.0"
#:package Tooark.AspNetCore@4.11.0
#addin nuget:?package=Tooark.AspNetCore&version=4.11.0
#tool nuget:?package=Tooark.AspNetCore&version=4.11.0
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
- Installation
- Components
- Usage Examples
- Dependencies
- Contributing
- Help & Security
- Support
- License
π Overview
The Tooark.AspNetCore package provides:
- extensions for ASP.NET Core types: the
ModelStateDictionaryandIFormFile; - conversion and validation of uploaded files, with the
IFormFileextensions ofFormFileExtension; - the
ResponseDtobody for validation failures in[ApiController]controllers, withAddTooarkModelStateEnvelope; - MVC validation of the
Tooark.Attributesattributes without the duplicated missing-field message, withAddTooarkValidationAttributes; - Problem Details (RFC 9457) for the
Tooark.Exceptionsexceptions, in controllers and minimal APIs, withAddTooarkProblemDetails; - results for minimal APIs that answer a notification or an exception with the same Problem Details, with
TooarkResults; - the place where the ASP.NET Core requirement was moved to, taking it out of the general-purpose packages;
- integration with the
Tooark.Extensionslocalizer, translating the validation error keys; - the intended home for 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 (aggregator) |
yes β by referencing the two 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();
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/aspnetinstead ofmcr.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 aResponseDto<object>, instead of ASP.NET Core'sValidationProblemDetails.
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 and ConvertValidationProblems on, the ASP.NET Core
column comes out with the Tooark errors list, translated.
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: useGetErrorsin 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 aTooark.Attributesattribute.
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 theTooark.Exceptionsexceptions answer with Problem Details (RFC 9457), in the status each exception defines, in controllers and minimal APIs.TooarkExceptionHandler: theIExceptionHandlerthe registration adds. It can be registered on its own withAddExceptionHandler<TooarkExceptionHandler>(), next toAddProblemDetails().ProblemDetailsError: an item of theerrorslist of the body, withcode,keyandmessage.TooarkProblemDetailsOptions: the log level of each handled exception and the conversion of the ASP.NET Core validation failures to theerrorslist.
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 by the
Tooark.Extensions localizer in the language
of the request.
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: with ConvertValidationProblems on, 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: Warning for a 4xx status, with the status and the message, and Error for a 5xx, with the exception
and its stack trace. A 404 or a 409 that is part of normal operation fills the log with warnings; to change the
level, per range or per status, configure TooarkProblemDetailsOptions:
builder.Services.Configure<TooarkProblemDetailsOptions>(options =>
{
options.ClientErrorLogLevel = LogLevel.Information; // 4xx (default: Warning)
options.ServerErrorLogLevel = LogLevel.Error; // 5xx (default)
options.StatusCodeLogLevels[StatusCodes.Status401Unauthorized] = LogLevel.Warning;
options.StatusCodeLogLevels[StatusCodes.Status404NotFound] = LogLevel.Debug;
});
The level of a status in StatusCodeLogLevels wins over the level of its range, and LogLevel.None leaves the
status out of the log. The options exist since v4.10.0, are code only (there is no configuration section) and keep
Warning as the 4xx default; v5 changes that default to Information.
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));
ASP.NET Core's own entry. On .NET 10 UseExceptionHandler does not log an exception that an
IExceptionHandler handled, so the Tooark entry is the only one. On .NET 8 the middleware logs every exception as
Error, in the Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware category, before calling the
handler: the Tooark level does not change that entry. Do not turn it off by category, since it is also the only
entry for the exceptions that are not Tooark's.
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:
with both in the same API, a client cannot tell from the key which format it received. With ConvertValidationProblems
on, 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.
builder.Services.AddTooarkProblemDetails();
builder.Services.Configure<TooarkProblemDetailsOptions>(options => options.ConvertValidationProblems = true);
// Without the conversion
{ "status": 400, "title": "One or more validation errors occurred.", "errors": { "Email": ["The Email field is required."] } }
// With the conversion
{ "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, .NET 10) |
Yes |
Results.ValidationProblem and TypedResults.ValidationProblem |
On .NET 10. On .NET 8 the framework writes the body itself: use TooarkResults |
The conversion is off on 4.x, because it changes the body clients receive, and is on by default from v5. 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 ConvertValidationProblems on, 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.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 codeT.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
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 aMemoryStream, 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.
They are extension methods on IFormFile, in the Tooark.AspNetCore.Files namespace, and exist 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. 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, .SVG 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.
Migration from Tooark.Utils. The Tooark.Utils methods that take an IFormFile are obsolete since v4.11.0
and removed in v5, together with its dependency on the Microsoft.AspNetCore.Http 2.x package. Each one has an
extension here, with the same rules:
Obsolete (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.
Filters and middlewares
Not shipped yet. 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 8 has the IExceptionHandler contract, which the UseExceptionHandler
middleware already calls, and implementing it was enough. When filters and middlewares exist, they 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 and the minimal API results in Tooark.AspNetCore.Results.
π 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.
π Dependencies
| Package | Version | Description |
|---|---|---|
Tooark.Attributes |
4.x | The attributes recognized by AddTooarkValidationAttributes |
Tooark.Dtos |
4.x | ResponseDto, the body of the validation response |
Tooark.Exceptions |
4.x | The exceptions answered with Problem Details, and their notification items |
Tooark.Extensions |
4.x | Error message localization |
Microsoft.AspNetCore.App (shared framework) |
8.x/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:
- π GitHub Sponsors
- β Ko-fi
Every contribution helps keep the project maintained and improving. Thank you! π
π License
This project is licensed under the BSD 3-Clause License.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. 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. |
-
net10.0
- Tooark.Attributes (>= 4.11.0)
- Tooark.Dtos (>= 4.11.0)
- Tooark.Exceptions (>= 4.11.0)
- Tooark.Extensions (>= 4.11.0)
-
net8.0
- Tooark.Attributes (>= 4.11.0)
- Tooark.Dtos (>= 4.11.0)
- Tooark.Exceptions (>= 4.11.0)
- Tooark.Extensions (>= 4.11.0)
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 |
|---|---|---|
| 4.11.0 | 0 | 11/21/2026 |
| 4.10.0 | 119 | 11/18/2026 |
| 4.9.0 | 131 | 11/16/2026 |
| 4.8.0 | 144 | 11/15/2026 |
| 4.7.3 | 125 | 11/11/2026 |
| 4.7.2 | 109 | 11/3/2026 |
| 4.7.1 | 152 | 10/17/2026 |
| 4.7.0 | 160 | 9/30/2026 |
| 4.6.0 | 170 | 9/29/2026 |
| 4.5.0 | 125 | 9/29/2026 |
| 4.4.0 | 126 | 9/28/2026 |
| 4.3.0 | 125 | 9/26/2026 |
| 4.2.1 | 132 | 9/25/2026 |
| 4.2.0 | 150 | 9/20/2026 |
| 4.1.0 | 122 | 9/18/2026 |
| 4.0.1 | 151 | 8/25/2026 |
| 4.0.0 | 137 | 8/25/2026 |