Hoe te gebruiken Async DICOM JSON Serialization in ASP.NET Core Web APIs

Hoe te gebruiken Async DICOM JSON Serialization in ASP.NET Core Web APIs

Deze tutorial toont aan hoe u async DICOM JSON serialisatie kunt gebruiken in ASP.NET Core web APIs. Asynk operaties zijn essentieel voor high-throughput web applicaties om thread blokkering te voorkomen en responsiviteit onder lading te behouden.

Waarom Async Serialization gebruiken?

  • Schalbaarheid:- Niet-blokkering I/O maakt het mogelijk om meer concurrerende verzoeken te behandelen.

    • De verantwoordelijkheid * :- Webserver blijft responsief tijdens het verwerken van grote bestanden.
    • Efficiëntie van de hulpbronnen*- Bedreigingen worden vrijgelaten terwijl we wachten op I/O-operaties.

Voorwaarden: het voorbereiden van het milieu

  • Installeer Visual Studio of een compatibele .NET IDE.
  • Creëer een nieuw ASP.NET Core Web API project gericht op .NET 8.
  • Installeer Aspose.Medical vanaf de NuGet Package Manager.

Step-by-Step Guide voor Async DICOM JSON Serialisatie

Stap 1: Installeer Aspose.Medical

Voeg de Aspose.Medische bibliotheek toe aan uw project met behulp van NuGet.

Install-Package Aspose.Medical

Stap 2: Inkluderen van noodzakelijke naamruimten

Voeg verwijzingen toe aan de vereiste naamruimten in uw controller.

using Aspose.Medical.Dicom;
using Aspose.Medical.Dicom.Serialization;
using Microsoft.AspNetCore.Mvc;

Stap 3: Het creëren van Async Deserialization Endpoint

Creëer een eindpunt dat JSON van het verzoek bod deserialisert.

[HttpPost("import")]
public async Task<IActionResult> ImportDicomJson()
{
    Dataset? dataset = await DicomJsonSerializer.DeserializeAsync(Request.Body);
    
    if (dataset == null)
        return BadRequest("Invalid DICOM JSON");
    
    return Ok("DICOM data imported successfully");
}

Stap 4: Creëren van Async Serialization Endpoint

Creëer een eindpunt dat DICOM naar JSON serialisert in de reactie.

[HttpGet("export/{filename}")]
public async Task ExportDicomJson(string filename)
{
    DicomFile dcm = DicomFile.Open($"storage/{filename}");
    
    Response.ContentType = "application/json";
    await DicomJsonSerializer.SerializeAsync(Response.Body, dcm.Dataset);
}

Stap 5: Handelen met annulering tokens

Pass annulering tokens voor de juiste verzoek annuleringsbehandeling.

[HttpPost("process")]
public async Task<IActionResult> ProcessDicomAsync(CancellationToken cancellationToken)
{
    Dataset? dataset = await DicomJsonSerializer.DeserializeAsync(
        Request.Body, 
        cancellationToken
    );
    
    if (cancellationToken.IsCancellationRequested)
        return StatusCode(499, "Client Closed Request");
    
    // Process dataset...
    return Ok();
}

Compleet ASP.NET Core Controller voorbeeld

Hier is een complete controller die de async DICOM JSON-operaties implementeert:

using Aspose.Medical.Dicom;
using Aspose.Medical.Dicom.Serialization;
using Microsoft.AspNetCore.Mvc;

namespace DicomApi.Controllers;

[ApiController]
[Route("api/[controller]")]
public class DicomController : ControllerBase
{
    private readonly string _storagePath = "dicom_storage";

    public DicomController()
    {
        Directory.CreateDirectory(_storagePath);
    }

    /// <summary>
    /// Import DICOM JSON and save as DICOM file
    /// </summary>
    [HttpPost("import")]
    public async Task<IActionResult> ImportDicomJson(CancellationToken cancellationToken)
    {
        try
        {
            Dataset? dataset = await DicomJsonSerializer.DeserializeAsync(
                Request.Body, 
                cancellationToken
            );

            if (dataset == null)
                return BadRequest("Failed to deserialize DICOM JSON");

            // Generate unique filename
            string filename = $"{Guid.NewGuid()}.dcm";
            string filepath = Path.Combine(_storagePath, filename);

            // Save as DICOM file
            DicomFile dcm = new DicomFile(dataset);
            dcm.Save(filepath);

            return Ok(new { message = "DICOM imported successfully", filename });
        }
        catch (OperationCanceledException)
        {
            return StatusCode(499, "Request cancelled");
        }
        catch (Exception ex)
        {
            return BadRequest($"Import failed: {ex.Message}");
        }
    }

    /// <summary>
    /// Export DICOM file as JSON stream
    /// </summary>
    [HttpGet("export/{filename}")]
    public async Task ExportDicomJson(string filename, CancellationToken cancellationToken)
    {
        string filepath = Path.Combine(_storagePath, filename);

        if (!System.IO.File.Exists(filepath))
        {
            Response.StatusCode = 404;
            await Response.WriteAsync("File not found");
            return;
        }

        try
        {
            DicomFile dcm = DicomFile.Open(filepath);
            
            Response.ContentType = "application/json";
            Response.Headers["Content-Disposition"] = $"attachment; filename=\"{filename}.json\"";
            
            await DicomJsonSerializer.SerializeAsync(
                Response.Body, 
                dcm.Dataset, 
                writeIndented: true
            );
        }
        catch (OperationCanceledException)
        {
            // Client disconnected
        }
        catch (Exception ex)
        {
            Response.StatusCode = 500;
            await Response.WriteAsync($"Export failed: {ex.Message}");
        }
    }

    /// <summary>
    /// Convert uploaded DICOM file to JSON
    /// </summary>
    [HttpPost("convert")]
    [RequestSizeLimit(100_000_000)] // 100MB limit
    public async Task ConvertDicomToJson(IFormFile file, CancellationToken cancellationToken)
    {
        if (file == null || file.Length == 0)
        {
            Response.StatusCode = 400;
            await Response.WriteAsync("No file uploaded");
            return;
        }

        try
        {
            // Save uploaded file temporarily
            string tempPath = Path.GetTempFileName();
            using (var stream = System.IO.File.Create(tempPath))
            {
                await file.CopyToAsync(stream, cancellationToken);
            }

            // Load and convert
            DicomFile dcm = DicomFile.Open(tempPath);
            
            Response.ContentType = "application/json";
            await DicomJsonSerializer.SerializeAsync(
                Response.Body, 
                dcm.Dataset, 
                writeIndented: true
            );

            // Cleanup temp file
            System.IO.File.Delete(tempPath);
        }
        catch (OperationCanceledException)
        {
            // Client disconnected
        }
        catch (Exception ex)
        {
            Response.StatusCode = 500;
            await Response.WriteAsync($"Conversion failed: {ex.Message}");
        }
    }
}

Configureren Request Size Limieten

Voor grote DICOM-bestanden, installeer aanvraaggrens in Program.cs:

var builder = WebApplication.CreateBuilder(args);

// Configure Kestrel for large uploads
builder.WebHost.ConfigureKestrel(options =>
{
    options.Limits.MaxRequestBodySize = 500_000_000; // 500MB
});

// Configure form options
builder.Services.Configure<FormOptions>(options =>
{
    options.MultipartBodyLengthLimit = 500_000_000;
});

var app = builder.Build();

Streamverwerking voorbeeld

Verwerken DICOM-bestanden zonder volledig in het geheugen te laden:

[HttpPost("stream-process")]
public async Task StreamProcessDicom(CancellationToken cancellationToken)
{
    // Read JSON from request body stream
    using var reader = new StreamReader(Request.Body);
    string json = await reader.ReadToEndAsync(cancellationToken);
    
    // Deserialize
    Dataset? dataset = DicomJsonSerializer.Deserialize(json);
    
    if (dataset == null)
    {
        Response.StatusCode = 400;
        await Response.WriteAsync("Invalid JSON");
        return;
    }
    
    // Process and stream response
    Response.ContentType = "application/json";
    await DicomJsonSerializer.SerializeAsync(
        Response.Body, 
        dataset, 
        writeIndented: true
    );
}

Foutbehandeling beste praktijken

Uitvoering van uitgebreide foutbehandeling:

[HttpPost("safe-import")]
public async Task<IActionResult> SafeImportDicomJson(CancellationToken cancellationToken)
{
    try
    {
        Dataset? dataset = await DicomJsonSerializer.DeserializeAsync(
            Request.Body, 
            cancellationToken
        );

        if (dataset == null)
            return BadRequest(new { error = "Invalid DICOM JSON format" });

        // Process dataset...
        return Ok(new { success = true });
    }
    catch (OperationCanceledException)
    {
        return StatusCode(499, new { error = "Request cancelled by client" });
    }
    catch (JsonException ex)
    {
        return BadRequest(new { error = "JSON parsing error", details = ex.Message });
    }
    catch (OutOfMemoryException)
    {
        return StatusCode(507, new { error = "File too large to process" });
    }
    catch (Exception ex)
    {
        return StatusCode(500, new { error = "Internal server error", details = ex.Message });
    }
}

Bijkomende beste praktijken

Gebruik verklaringen voor streams

Gebruik altijd de juiste ontwerppatronen:

using (FileStream fs = System.IO.File.OpenRead(filepath))
{
    // Process stream
}

Timeout configuratie

Configureer geschikte timouts voor lange operaties:

builder.WebHost.ConfigureKestrel(options =>
{
    options.Limits.RequestHeadersTimeout = TimeSpan.FromMinutes(2);
    options.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(5);
});

Aanvullende informatie

  • Async-methoden verbeteren schaalbaarheid, maar versnellen niet noodzakelijkerwijs individuele verzoeken.
  • Gebruik annuleringstoekens om cliëntverbindingen correct te beheren.
  • Monitoring van het geheugengebruik bij het verwerken van grote DICOM-bestanden.

Conclusie

Deze tutorial heeft aangetoond hoe te implementeren async DICOM JSON serialisatie in ASP.NET Core web API’s met behulp van Aspose.Medical.

 Nederlands