Essential Components for Blazor Server Apps with Azure Entra
AI Store에서 AI코딩으로 만들어진 앱을 만나보세요!
지금 바로 방문하기

Blazor Server 앱을 위한 필수 구성 요소

카테고리

프로그래밍/소프트웨어 개발

서브카테고리

웹 개발

대상자

- C# 개발자 및 Blazor Server 프로젝트를 구축 중인 개발자

- Azure Entra 인증 및 로깅, 요청 추적, 예외 처리에 대한 실무 적용이 필요한 중급~고급 개발자

- .NET 8 기반의 Blazor Web App 모델을 사용하는 개발자

핵심 요약

  • Azure Entra 인증 통합을 통해 보안 강화 (Azure Entra Authentication 사용)
  • Serilog를 활용한 강력한 로깅 구현 (Serilog.AspNetCore 패키지 사용)
  • Correlation ID 생성 및 전달로 요청 흐름 추적 가능 (ICorrelationService 인터페이스 활용)
  • Polly를 통한 HTTP 요청 재시도 정책 설정 (5회 재시도, 지수적 지연 시간 적용)

섹션별 세부 요약

1. 소개

  • Blazor Server는 SignalR을 기반으로 서버 렌더링을 수행하며, .NET 8에서 Blazor Web App 모델과 통합 가능
  • 주요 초점: Azure Entra 인증, 로깅, 예외 처리, 요청 추적

2. 프로젝트 구조

  • BasicDataModels/: appSettings의 JSON 값(예: JWT 파라미터, API 호스트)을 위한 모델
  • Extensions/: HttpClientExtension을 통한 API 요청 처리 (성공/실패 처리)
  • Middleware/: Correlation ID 생성 (요청 흐름 추적을 위한 전역 고유 ID)
  • Services/: API 호출을 위한 서비스 구현 (인터페이스 패턴 사용, 예: Azure Graph, Workflow 등)

3. 인증 설정

  • Azure Entra 인증을 통한 사용자 관리 (기존 포스트 참조)
  • 인증 설정은 Azure Active Directory와의 연동이 필수

4. 로깅 설정 (Serilog)

  • Serilog.AspNetCore 사용: Serilog 구성 예시

```json

"Serilog": {

"MinimumLevel": { "Default": "Information" },

"WriteTo": [

{

"Name": "File",

"Args": {

"path": "D:\\ApplicationLogs\\templateUILogs.txt",

"outputTemplate": "[CorrId:{CorrelationId}] [{Timestamp:yyyy-MM-dd HH:mm:ss.fff} {Level:u3}] {Message:lj}{NewLine}{Exception}"

}

}

]

}

```

  • LogContext.PushProperty("CorrelationId", ...): 로그에 Correlation ID 추가

5. Correlation ID 구현

  • ICorrelationService 인터페이스 정의
  • CorrelationCircuitHandler 생성:

```csharp

public class CorrelationCircuitHandler : CircuitHandler

{

public override Task OnCircuitOpenedAsync(Circuit circuit, CancellationToken cancellationToken)

{

_correlationService.CorrelationId = circuit.Id;

LogContext.PushProperty("CorrelationId", _correlationService.CorrelationId);

return Task.CompletedTask;

}

}

```

  • 서비스 등록:

```csharp

services.AddScoped();

services.AddScoped();

```

6. 예외 처리 (Custom Exception Logging)

  • IExceptionLoggingService 인터페이스 정의
  • ExceptionLoggingService 구현:

```csharp

public class ExceptionLoggingService : DelegatingHandler, IExceptionLoggingService

{

public ProblemDetails Log(Exception exception)

{

var problemDetails = new ProblemDetails

{

StatusCode = StatusCodes.Status500InternalServerError,

FileName = exception.TargetSite?.DeclaringType?.FullName,

LineNumber = stackTrace.GetFrame(0)?.GetFileLineNumber(),

MethodName = exception.TargetSite?.Name,

Type = exception.GetType().Name,

Title = exception.Message,

Description = exception.InnerException?.Message,

StackTrace = exception.StackTrace

};

LogContext.PushProperty("CorrelationId", _correlationService.CorrelationId);

return problemDetails;

}

}

```

  • 서비스 등록:

```csharp

services.AddScoped();

```

7. 재시도 정책 (Polly)

  • Polly를 통한 HTTP 요청 재시도:

```csharp

services.AddHttpClient("TemplateClient", client => client.BaseAddress = new Uri(baseUrls.TemplateApiBaseUrl))

.AddTransientHttpErrorPolicy(policyBuilder =>

policyBuilder.WaitAndRetryAsync(5, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))));

```

  • 5회 재시도, 지수적 지연 시간 적용 (2초 → 4초 → 8초 ...)

8. 요청 제한 (Rate Limiting)

  • AddRateLimiter를 통한 요청 제한 설정 예시:

```csharp

services.AddRateLimiter(options =>

options.AddFixedWindowLimiter("fixed", opt =>

{ opt.PermitLimit = 12; opt.Window = TimeSpan.FromSeconds(5); }));

```

결론

  • Correlation ID 생성 및 전달을 통해 요청 흐름 추적 가능
  • Serilog보안하고 강력한 로깅 구현
  • Polly를 활용한 HTTP 요청 재시도 정책 설정 (5회 재시도)
  • Rate Limiter를 통해 요청 과부하 방지 가능
  • Azure Entra 인증예외 처리 서비스를 통합하여 안정적인 Blazor Server 앱 구축 가능