최소 API 프로젝트를위한 헬기 라이브러리 모음.
반사를 사용한 자동 엔드 포인트 등록을위한 최소 API 프로젝트를위한 라우팅 도우미를 제공하는 라이브러리.
도서관은 Nuget에서 구입할 수 있습니다. Package Manager 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 객체 에서 MapEndpoints() 확장 메소드를 호출하십시오.
// using MinimalHelpers.Routing;
app . MapEndpoints ( ) ;
app . Run ( ) ; 기본적으로 MapEndpoints() 호출 어셈블리를 스캔하여 IEndpointRouteHandlerBuilder 인터페이스를 구현하는 클래스를 검색합니다. 경로 처리기가 다른 어셈블리에 정의 된 경우 두 가지 대안이 있습니다.
MapEndpoints() 오버로드를 사용하십시오.MapEndpointsFromAssemblyContaining<T>() 확장 방법을 사용하고 스캔하려는 어셈블리에 포함 된 유형을 지정하십시오. 또한 실제로 맵핑하려는 유형 ( IRouteEndpointHandlerBuilder 인터페이스 MapEndpoints 구현하는 유형 중)을 명시 적으로 결정할 수 있습니다.
app . MapEndpoints ( type =>
{
if ( type . Name . StartsWith ( "Products" ) )
{
return false ;
}
return true ;
} ) ;이러한 방법은 반사에 의존하여 어셈블리를 스캔하고
IEndpointRouteHandlerBuilder인터페이스를 구현하는 클래스를 찾습니다. 이것은 특히 대규모 프로젝트에서 성능에 영향을 줄 수 있습니다. 성능 문제가있는 경우 명시 적 등록 방법을 사용하는 것을 고려하십시오. 또한,이 솔루션은 기본 AOT와 호환성이 없습니다.
최소 API 프로젝트에서 자동 엔드 포인트 등록을위한 소스 생성기를 제공하는 라이브러리.
도서관은 Nuget에서 구입할 수 있습니다. Package Manager 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 객체 에서 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 ) ; 최소 API 프로젝트를위한 엔드 포인트 필터를 제공하여 Minivalidation 라이브러리를 사용하여 데이터 주석으로 유효성 검사를 수행하는 라이브러리.
도서관은 Nuget에서 구입할 수 있습니다. Package Manager GUI 의 Validation을 검색하거나 .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)" ;
} ) ; 예를 들어 ROSX 파일을 사용하여 응답의 title 속성을 로컬화하려는 경우 ValidationErrorTitleMessageFactory 를 사용할 수 있습니다.
FluentValidation을 사용하여 유효성 검사를 수행하기 위해 최소 API 프로젝트를위한 엔드 포인트 필터를 제공하는 라이브러리.
도서관은 Nuget에서 구입할 수 있습니다. Package Manager GUI 의 MinimalHelpers.fluentValidation을 검색하거나 .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)" ;
} ) ; 예를 들어 ROSX 파일을 사용하여 응답의 title 속성을 로컬화하려는 경우 ValidationErrorTitleMessageFactory 를 사용할 수 있습니다.
기여하다
프로젝트는 끊임없이 발전하고 있습니다. 기부금을 환영합니다. 레포에 문제를 제출하고 요청을 가져 오면 가능한 한 해결하겠습니다.