refactor(api): migrate controllers to Stream API with Base64 validation
PdfValidationController: - ValidateFromFile: IFormFile.OpenReadStream() direct usage (no byte[] copy) - ValidateFromBase64: try-catch Convert.FromBase64String → BadRequestException - ValidatePdfAFromFile: IFormFile.OpenReadStream() direct usage - ValidatePdfAFromBase64: try-catch Convert.FromBase64String → BadRequestException PdfAttachmentController: - CheckAttachmentsFromBase64: try-catch Convert.FromBase64String → BadRequestException SwissQrCodeController: - ExtractFromBase64: try-catch Convert.FromBase64String → BadRequestException All controllers: Add using DocumentOperator.Domain.Common.Exceptions for BadRequestException
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
using DocumentOperator.Application.CheckPdfAttachments.Queries;
|
||||
using DocumentOperator.Application.Common.DTOs;
|
||||
using DocumentOperator.Domain.Common.Exceptions;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
@@ -33,13 +34,11 @@ public class PdfAttachmentController(IMediator mediator) : ControllerBase
|
||||
IFormFile file,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
// Convert IFormFile to byte array
|
||||
using var memoryStream = new MemoryStream();
|
||||
await file.CopyToAsync(memoryStream, cancellationToken);
|
||||
byte[] pdfBytes = memoryStream.ToArray();
|
||||
// Use IFormFile stream directly (no intermediate byte[] conversion)
|
||||
using var pdfStream = file.OpenReadStream();
|
||||
|
||||
// Send query to MediatR (ValidationBehavior runs automatically)
|
||||
var query = new CheckPdfAttachmentsQuery { PdfBytes = pdfBytes };
|
||||
var query = new CheckPdfAttachmentsQuery { PdfStream = pdfStream };
|
||||
var result = await mediator.Send(query, cancellationToken);
|
||||
|
||||
return Ok(result);
|
||||
@@ -64,8 +63,21 @@ public class PdfAttachmentController(IMediator mediator) : ControllerBase
|
||||
[FromBody] CheckPdfAttachmentsRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
// Convert Base64 to stream (wrap in try-catch to throw BadRequestException)
|
||||
byte[] pdfBytes;
|
||||
try
|
||||
{
|
||||
pdfBytes = Convert.FromBase64String(request.Base64Pdf);
|
||||
}
|
||||
catch (FormatException ex)
|
||||
{
|
||||
throw new BadRequestException("Invalid Base64 format: " + ex.Message);
|
||||
}
|
||||
|
||||
using var pdfStream = new MemoryStream(pdfBytes);
|
||||
|
||||
// Send query to MediatR (ValidationBehavior runs automatically)
|
||||
var query = new CheckPdfAttachmentsQuery { Base64Pdf = request.Base64Pdf };
|
||||
var query = new CheckPdfAttachmentsQuery { PdfStream = pdfStream };
|
||||
var result = await mediator.Send(query, cancellationToken);
|
||||
|
||||
return Ok(result);
|
||||
|
||||
Reference in New Issue
Block a user