ASPNET 7 - Endpoint Filter

2022. 12. 12. 00:00ASPNET/ASPNET 7

반응형

최소 API 필터를 통해 개발자는 다음을 지원하는 비즈니스 논리를 구현할 수 있다.

  • 엔드포인트 처리기 전후에 코드 실행
  • 엔드포인트 처리기 호출 중에 제공된 매개 변수 검사 및 수정
  • 엔드포인트 처리기의 응답 동작 가로채기

필터는 다음 시나리오에서 유용할 수 있다.

  • 엔드포인트로 전송되는 요청 매개 변수 및 본문의 유효성 검사
  • 요청 및 응답에 대한 정보 로깅
  • 요청이 지원되는 API 버전을 대상으로 하는지 확인

다음과 같은 형태로 Filter 를 지정할 수 있다. 

var builder = WebApplication.CreateBuilder(args);

var app = builder.Build();

string ColorName(string color) => $"Color specified: {color}!";

app.MapGet("/colorSelector/{color}", ColorName)
    .AddEndpointFilter(async (invocationContext, next) =>
    {
        var color = invocationContext.GetArgument<string>(0);

        if (color == "Red")
        {
            return Results.Problem("Red not allowed!");
        }
        return await next(invocationContext);
    });

app.Run();
  • AddEndpointFilter 를 통해 Filter 를 설정 한다. 
  • Red 값을 제외하고 지정된 색을 반환한다. 
  • next 를 호출해 다음 파이프라인 또는 다음 필터를 호출 한다. 

필터가 처리기에서 처리되는 순서는 아래 코드를 보면 이해 가능 하다. 

next 가 호출되기전에는 FIFO 이고

next 가 호출된 이후에서 FILO 이다. 

 

그림으로 보면 아래와 같은 순서가 되는 거다.

 

var builder = WebApplication.CreateBuilder(args);

var app = builder.Build();

app.MapGet("/", () =>
    {
        app.Logger.LogInformation("             Endpoint");
        return "Test of multiple filters";
    })
    .AddEndpointFilter(async (efiContext, next) =>
    {
        app.Logger.LogInformation("Before first filter");
        var result = await next(efiContext);
        app.Logger.LogInformation("After first filter");
        return result;
    })
    .AddEndpointFilter(async (efiContext, next) =>
    {
        app.Logger.LogInformation(" Before 2nd filter");
        var result = await next(efiContext);
        app.Logger.LogInformation(" After 2nd filter");
        return result;
    })
    .AddEndpointFilter(async (efiContext, next) =>
    {
        app.Logger.LogInformation("     Before 3rd filter");
        var result = await next(efiContext);
        app.Logger.LogInformation("     After 3rd filter");
        return result;
    });

app.Run();

실행 하면 순서에 의해 다음과 같이 Logge 가 남겨진다. 

Before first filter
    Before 2nd filter
        Before 3rd filter
            Endpoint
        After 3rd filter
    After 2nd filter
After first filter

 

이러한 filter 를 사용하면 API 실행 이전 이나 이후에 다른 동작을 할 수 있게 된다. 

 

컨트롤러에 filter 를 등록 하고 싶다면 아래와 같이 처리 한다. 

var builder = WebApplication.CreateBuilder(args);

var app = builder.Build();

app.MapController()
    .AddEndpointFilter(async (efiContext, next) =>
    {
        efiContext.HttpContext.Items["endpointFilterCalled"] = true;
        var result = await next(efiContext);
        return result;
    });

app.Run();

 

관련영상

https://youtu.be/UkJQd7QROjE

 

반응형

'ASPNET > ASPNET 7' 카테고리의 다른 글

Rest API Template 만들기 - EP 01 (Create , Swagger, Logging)  (0) 2022.12.19
gRPC HealthCheck  (0) 2022.12.15
ASPNET 7 - Authentication  (0) 2022.12.08
ASPNET 7 - Route Group and Swagger  (0) 2022.12.05
ASPNET 7 - Rate Limit  (0) 2022.12.01