最小限のAPIプロジェクトのためのヘルパーライブラリのコレクション。
リフレクションを使用した自動エンドポイント登録用の最小限のAPIプロジェクトのルーティングヘルパーを提供するライブラリ。
ライブラリはNugetで利用できます。 MinimalHelpers.RoutingをパッケージマネージャーGUIで検索するか、 .NET CLIで次のコマンドを実行します。
dotnet add package MinimalHelpers.Routingルートハンドラーの登録を保持するクラスを作成し、 IEndpointRouteHandlerBuilderインターフェイスを実装するようにします。
public class PeopleEndpoints : MinimalHelpers . Routing . IEndpointRouteHandlerBuilder
{
public static void MapEndpoints ( IEndpointRouteBuilder endpoints )
{
endpoints . MapGet ( "/api/people" , GetList ) ;
endpoints . MapGet ( "/api/people/{id:guid}" , Get ) ;
endpoints . MapPost ( "/api/people" , Insert ) ;
endpoints . MapPut ( "/api/people/{id:guid}" , Update ) ;
endpoints . MapDelete ( "/api/people/{id:guid}" , Delete ) ;
}
// ...
} Run()メソッドの呼び出しの前にwebApplicationオブジェクト内のwebApplicationオブジェクト内のwebApplicationオブジェクトにMapEndpoints()拡張メソッドを呼び出します。
// using MinimalHelpers.Routing;
app . MapEndpoints ( ) ;
app . Run ( ) ;デフォルトでは、 MapEndpoints()呼び出しアセンブリをスキャンして、 IEndpointRouteHandlerBuilderインターフェイスを実装するクラスを検索します。ルートハンドラーが別のアセンブリで定義されている場合、2つの選択肢があります。
MapEndpoints()オーバーロードを使用しますMapEndpointsFromAssemblyContaining<T>()を使用し、スキャンするアセンブリに含まれるタイプを指定しますまた、実際にMapEndpointsしたいタイプ( IRouteEndpointHandlerBuilderインターフェイスを実装するタイプの中で)を明示的に決定することもできます。
app . MapEndpoints ( type =>
{
if ( type . Name . StartsWith ( "Products" ) )
{
return false ;
}
return true ;
} ) ;これらのメソッドは反射に依存してアセンブリをスキャンし、
IEndpointRouteHandlerBuilderインターフェイスを実装するクラスを見つけます。これは、特に大規模なプロジェクトでパフォーマンスに影響を与える可能性があります。パフォーマンスの問題がある場合は、明示的な登録方法の使用を検討してください。さらに、このソリューションはネイティブAOTと非互換性があります。
最小限のAPIプロジェクトでの自動エンドポイント登録用のソースジェネレーターを提供するライブラリ。
ライブラリはNugetで利用できます。 MinimalHelpers.RoutingをパッケージマネージャーGUIで検索するか、 .NET CLIで次のコマンドを実行します。
dotnet add package MinimalHelpers.Routing.Analyzersルートハンドラーの登録を保持するクラスを作成し、 IEndpointRouteHandlerBuilderインターフェイスを実装するようにします。
public class PeopleEndpoints : IEndpointRouteHandlerBuilder
{
public static void MapEndpoints ( IEndpointRouteBuilder endpoints )
{
endpoints . MapGet ( "/api/people" , GetList ) ;
endpoints . MapGet ( "/api/people/{id:guid}" , Get ) ;
endpoints . MapPost ( "/api/people" , Insert ) ;
endpoints . MapPut ( "/api/people/{id:guid}" , Update ) ;
endpoints . MapDelete ( "/api/people/{id:guid}" , Delete ) ;
}
// ...
}注Minimalhelpers.routing.analyzersパッケージのみを使用する必要があることに注意してください。このソースジェネレーターを使用すると、
IEndpointRouteHandlerBuilderインターフェイスが自動生成されます。
Run()メソッドの呼び出しの前にwebApplicationオブジェクト内のwebApplicationオブジェクト内のwebApplicationオブジェクトにMapEndpoints()拡張メソッドを呼び出します。
app . MapEndpoints ( ) ;
app . Run ( ) ;注
MapEndpointsメソッドは、ソースジェネレーターによって生成されます。
最小限のAPIプロジェクトにOpenapiヘルパーを提供するライブラリ。
ライブラリはNugetで利用できます。パッケージマネージャーGUIでMinimalHelpers.openapiを検索するか、 .NET CLIで次のコマンドを実行します。
dotnet add package MinimalHelpers.OpenApiOpenapiの拡張方法
このライブラリは、最小限のAPIプロジェクトでOpenAPI構成を簡素化するいくつかの拡張メソッドを提供します。たとえば、ステータスコードを使用して応答の説明をカスタマイズすることができます。
endpoints . MapPost ( "login" , LoginAsync )
. AllowAnonymous ( )
. WithValidation < LoginRequest > ( )
. Produces < LoginResponse > ( StatusCodes . Status200OK )
. Produces < LoginResponse > ( StatusCodes . Status206PartialContent )
. Produces ( StatusCodes . Status403Forbidden )
. ProducesValidationProblem ( )
. WithOpenApi ( operation =>
{
operation . Summary = "Performs the login of a user" ;
operation . Response ( StatusCodes . Status200OK ) . Description = "Login successful" ;
operation . Response ( StatusCodes . Status206PartialContent ) . Description = "The user is logged in, but the password has expired and must be changed" ;
operation . Response ( StatusCodes . Status400BadRequest ) . Description = "Incorrect username and/or password" ;
operation . Response ( StatusCodes . Status403Forbidden ) . Description = "The user was blocked due to too many failed logins" ;
return operation ;
} ) ;routehandlerbuilderの拡張方法
多くの場合、複数の4xx戻り値を持つエンドポイントがあり、それぞれがProblemDetails応答を生成します。
endpoints . MapGet ( "/api/people/{id:guid}" , Get )
. ProducesProblem ( StatusCodes . Status400BadRequest )
. ProducesProblem ( StatusCodes . Status401Unauthorized )
. ProducesProblem ( StatusCodes . Status403Forbidden )
. ProducesProblem ( StatusCodes . Status404NotFound ) ; ProducesProblemための複数の呼び出しを回避するために、ライブラリが提供するProducesDefaultProblem拡張法を使用できます。
endpoints . MapGet ( "/api/people/{id:guid}" , Get )
. ProducesDefaultProblem ( StatusCodes . Status400BadRequest , StatusCodes . Status401Unauthorized ,
StatusCodes . Status403Forbidden , StatusCodes . Status404NotFound ) ; Minivalidationライブラリを使用して、データアノテーションを使用して検証を実行するための最小限のAPIプロジェクトのエンドポイントフィルターを提供するライブラリ。
ライブラリはNugetで利用できます。 MinimalHelpers.validationをパッケージマネージャーGUIで検索するか、 .NET CLIで次のコマンドを実行します。
dotnet add package MinimalHelpers.Validation検証ルールを定義する属性を持つクラスを装飾します。
using System . ComponentModel . DataAnnotations ;
public class Person
{
[ Required ]
[ MaxLength ( 20 ) ]
public string ? FirstName { get ; set ; }
[ Required ]
[ MaxLength ( 20 ) ]
public string ? LastName { get ; set ; }
[ MaxLength ( 50 ) ]
public string ? City { get ; set ; }
} WithValidation<T>()拡張メソッドを追加して、検証フィルターを有効にします。
using MinimalHelpers . Validation ;
app . MapPost ( "/api/people" , ( Person person ) =>
{
// ...
} )
. WithValidation < Person > ( ) ;検証が失敗した場合、応答は、検証エラーを含むValidationProblemDetailsオブジェクトを使用して400 Bad Requestになります。
{
"type" : " https://tools.ietf.org/html/rfc9110#section-15.5.1 " ,
"title" : " One or more validation errors occurred " ,
"status" : 400 ,
"instance" : " /api/people " ,
"traceId" : " 00-009c0162ba678cae2ee391815dbbb59d-0a3a5b0c16d053e6-00 " ,
"errors" : {
"FirstName" : [
" The field FirstName must be a string or array type with a maximum length of '20'. "
],
"LastName" : [
" The LastName field is required. "
]
}
}検証をカスタマイズする場合は、 ConfigureValidation拡張法を使用できます。
using MinimalHelpers . Validation ;
builder . Services . ConfigureValidation ( options =>
{
// If you want to get errors as a list instead of a dictionary.
options . ErrorResponseFormat = ErrorResponseFormat . List ;
// The default is "One or more validation errors occurred"
options . ValidationErrorTitleMessageFactory =
( context , errors ) => $ "There was { errors . Values . Sum ( v => v . Length ) } error(s)" ;
} ) ;たとえば、Resxファイルを使用して応答のtitleプロパティをローカライズしたい場合、 ValidationErrorTitleMessageFactoryを使用できます。
FluentValidationを使用して検証を実行するための最小限のAPIプロジェクトのエンドポイントフィルターを提供するライブラリ。
ライブラリはNugetで利用できます。 MinimalHelpers.FluentValidationをパッケージマネージャーGUIで検索するか、 .NET CLIで次のコマンドを実行します。
dotnet add package MinimalHelpers.FluentValidationAbstractValidatorを拡張し、検証ルールを定義するクラスを作成します。
using FluentValidation ;
public record class Product ( string Name , string Description , double UnitPrice ) ;
public class ProductValidator : AbstractValidator < Product >
{
public ProductValidator ( )
{
RuleFor ( p => p . Name ) . NotEmpty ( ) . MaximumLength ( 50 ) . EmailAddress ( ) ;
RuleFor ( p => p . Description ) . MaximumLength ( 500 ) ;
RuleFor ( p => p . UnitPrice ) . GreaterThan ( 0 ) ;
}
}サービスコレクションにバリデーターを登録してください:
using FluentValidation ;
// Assuming the validators are in the same assembly as the Program class
builder . Services . AddValidatorsFromAssemblyContaining < Program > ( ) ; WithValidation<T>()拡張メソッドを追加して、検証フィルターを有効にします。
using MinimalHelpers . FluentValidation ;
app . MapPost ( "/api/products" , ( Product product ) =>
{
// ...
} )
. WithValidation < Product > ( ) ;検証が失敗した場合、応答は、検証エラーを含むValidationProblemDetailsオブジェクトを使用して400 Bad Requestになります。
{
"type" : " https://tools.ietf.org/html/rfc9110#section-15.5.1 " ,
"title" : " One or more validation errors occurred " ,
"status" : 400 ,
"instance" : " /api/products " ,
"traceId" : " 00-f4ced0ae470424dd04cbcebe5f232dc5-bbdcc59f310ebfb8-00 " ,
"errors" : {
"Name" : [
" 'Name' cannot be empty. "
],
"UnitPrice" : [
" 'Unit Price' must be grater than '0'. "
]
}
}検証をカスタマイズする場合は、 ConfigureValidation拡張法を使用できます。
using MinimalHelpers . Validation ;
builder . Services . ConfigureValidation ( options =>
{
// If you want to get errors as a list instead of a dictionary.
options . ErrorResponseFormat = ErrorResponseFormat . List ;
// The default is "One or more validation errors occurred"
options . ValidationErrorTitleMessageFactory =
( context , errors ) => $ "There was { errors . Values . Sum ( v => v . Length ) } error(s)" ;
} ) ;たとえば、Resxファイルを使用して応答のtitleプロパティをローカライズしたい場合、 ValidationErrorTitleMessageFactoryを使用できます。
貢献する
このプロジェクトは常に進化しています。貢献は大歓迎です。リポジトリに問題やリクエストを提出してください。できる限り説明します。