Kumpulan perpustakaan pembantu untuk proyek API minimal.
Perpustakaan yang menyediakan pembantu perutean untuk proyek API minimal untuk pendaftaran titik akhir otomatis menggunakan refleksi.
Perpustakaan tersedia di Nuget. Cukup cari minimalhelpers. Mengutip di GUI Manajer Paket atau jalankan perintah berikut di .NET CLI :
dotnet add package MinimalHelpers.Routing Buat kelas untuk menahan pendaftaran penangan rute Anda dan membuatnya menerapkan antarmuka 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 ) ;
}
// ...
} Hubungi metode ekstensi MapEndpoints() pada objek WebApplication di dalam Program.cs sebelum Metode Run() Doa:
// using MinimalHelpers.Routing;
app . MapEndpoints ( ) ;
app . Run ( ) ; Secara default, MapEndpoints() akan memindai rakitan panggilan untuk mencari kelas yang mengimplementasikan antarmuka IEndpointRouteHandlerBuilder . Jika penangan rute Anda didefinisikan dalam majelis lain, Anda memiliki dua alternatif:
MapEndpoints() yang mengambil perakitan untuk memindai sebagai argumenMapEndpointsFromAssemblyContaining<T>() dan tentukan jenis yang terkandung dalam rakitan yang ingin Anda pindai Anda juga dapat secara eksplisit memutuskan jenis apa (di antara yang mengimplementasikan antarmuka IRouteEndpointHandlerBuilder ) Anda ingin benar -benar memetakan, meneruskan predikat ke metode MapEndpoints :
app . MapEndpoints ( type =>
{
if ( type . Name . StartsWith ( "Products" ) )
{
return false ;
}
return true ;
} ) ;Perhatikan metode ini bergantung pada refleksi untuk memindai perakitan dan menemukan kelas -kelas yang mengimplementasikan antarmuka
IEndpointRouteHandlerBuilder. Ini dapat memiliki dampak kinerja, terutama dalam proyek besar. Jika Anda memiliki masalah kinerja, pertimbangkan untuk menggunakan metode pendaftaran eksplisit. Selain itu, solusi ini tidak kompatibil dengan AOT asli.
Perpustakaan yang menyediakan generator sumber untuk pendaftaran titik akhir otomatis dalam proyek API minimal.
Perpustakaan tersedia di Nuget. Cukup cari minimalhelpers. Mengutip di GUI Manajer Paket atau jalankan perintah berikut di .NET CLI :
dotnet add package MinimalHelpers.Routing.Analyzers Buat kelas untuk menahan pendaftaran penangan rute Anda dan membuatnya menerapkan antarmuka 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 ) ;
}
// ...
}Perhatikan Anda hanya perlu menggunakan paket minimalhelpers.Routing.Analyzers . Dengan generator sumber ini, antarmuka
IEndpointRouteHandlerBuilderdihasilkan secara otomatis.
Hubungi metode ekstensi MapEndpoints() pada objek WebApplication di dalam Program.cs sebelum Metode Run() Doa:
app . MapEndpoints ( ) ;
app . Run ( ) ;Perhatikan metode
MapEndpointsdihasilkan oleh generator sumber.
Perpustakaan yang menyediakan pembantu OpenAPI untuk proyek API minimal.
Perpustakaan tersedia di Nuget. Cukup cari minimalhelpers.openapi di manajer paket GUI atau jalankan perintah berikut di .net CLI :
dotnet add package MinimalHelpers.OpenApiMetode ekstensi untuk openapi
Perpustakaan ini menyediakan beberapa metode ekstensi yang menyederhanakan konfigurasi OpenAPI dalam proyek API minimal. Misalnya, dimungkinkan untuk menyesuaikan deskripsi respons menggunakan kode statusnya:
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 ;
} ) ;Metode ekstensi untuk routehandlerbuilder
Seringkali kita memiliki titik akhir dengan beberapa nilai pengembalian 4xx, yang masing -masing menghasilkan respons ProblemDetails :
endpoints . MapGet ( "/api/people/{id:guid}" , Get )
. ProducesProblem ( StatusCodes . Status400BadRequest )
. ProducesProblem ( StatusCodes . Status401Unauthorized )
. ProducesProblem ( StatusCodes . Status403Forbidden )
. ProducesProblem ( StatusCodes . Status404NotFound ) ; Untuk menghindari beberapa panggilan untuk ProducesProblem , kami dapat menggunakan metode ekstensi ProducesDefaultProblem yang disediakan oleh perpustakaan:
endpoints . MapGet ( "/api/people/{id:guid}" , Get )
. ProducesDefaultProblem ( StatusCodes . Status400BadRequest , StatusCodes . Status401Unauthorized ,
StatusCodes . Status403Forbidden , StatusCodes . Status404NotFound ) ; Perpustakaan yang menyediakan filter titik akhir untuk proyek API minimal untuk melakukan validasi dengan anotasi data, menggunakan Minivalidation Library.
Perpustakaan tersedia di Nuget. Cukup cari minimalhelpers.Validation di Paket Manajer GUI atau jalankan perintah berikut di .NET CLI :
dotnet add package MinimalHelpers.ValidationMenghiasi kelas dengan atribut untuk menentukan aturan validasi:
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 ; }
} Tambahkan metode ekstensi WithValidation<T>() untuk mengaktifkan filter validasi:
using MinimalHelpers . Validation ;
app . MapPost ( "/api/people" , ( Person person ) =>
{
// ...
} )
. WithValidation < Person > ( ) ; Jika validasi gagal, respons akan menjadi 400 Bad Request dengan objek ValidationProblemDetails yang berisi kesalahan validasi, misalnya:
{
"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. "
]
}
} Jika Anda ingin menyesuaikan validasi, Anda dapat menggunakan metode ekstensi 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)" ;
} ) ; Anda dapat menggunakan ValidationErrorTitleMessageFactory , misalnya, jika Anda ingin melokalisasi properti title dari respons menggunakan file resx.
Perpustakaan yang menyediakan filter titik akhir untuk proyek API minimal untuk melakukan validasi menggunakan fluentvalidasi.
Perpustakaan tersedia di Nuget. Cukup cari minimalhelpers.fluentValidation di Paket Manajer GUI atau jalankan perintah berikut di .NET CLI :
dotnet add package MinimalHelpers.FluentValidationBuat kelas yang memperluas AbstractValidator dan tentukan aturan validasi:
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 ) ;
}
}Daftar validator dalam pengumpulan layanan:
using FluentValidation ;
// Assuming the validators are in the same assembly as the Program class
builder . Services . AddValidatorsFromAssemblyContaining < Program > ( ) ; Tambahkan metode ekstensi WithValidation<T>() untuk mengaktifkan filter validasi:
using MinimalHelpers . FluentValidation ;
app . MapPost ( "/api/products" , ( Product product ) =>
{
// ...
} )
. WithValidation < Product > ( ) ; Jika validasi gagal, respons akan menjadi 400 Bad Request dengan objek ValidationProblemDetails yang berisi kesalahan validasi, misalnya:
{
"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'. "
]
}
} Jika Anda ingin menyesuaikan validasi, Anda dapat menggunakan metode ekstensi 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)" ;
} ) ; Anda dapat menggunakan ValidationErrorTitleMessageFactory , misalnya, jika Anda ingin melokalisasi properti title dari respons menggunakan file resx.
Menyumbang
Proyek ini terus berkembang. Kontribusi dipersilakan. Jangan ragu untuk mengajukan masalah dan menarik permintaan pada repo dan kami akan mengatasinya.