How to Use Async DICOM JSON Serialization in ASP.NET Core Web APIs
This tutorial demonstrates how to use async DICOM JSON serialization in ASP.NET Core web APIs. Async operations are essential for high-throughput web applications to prevent thread blocking and maintain responsiveness under load.
Why Use Async Serialization?
- Scalability:
- Non-blocking I/O allows handling more concurrent requests.
- Responsiveness:
- Web server remains responsive during large file processing.
- Resource Efficiency:
- Threads are released while waiting for I/O operations.
Prerequisites: Preparing the Environment
- Set up Visual Studio or any compatible .NET IDE.
- Create a new ASP.NET Core Web API project targeting .NET 8.
- Install Aspose.Medical from the NuGet Package Manager.
Step-by-Step Guide to Async DICOM JSON Serialization
Step 1: Install Aspose.Medical
Add the Aspose.Medical library to your project using NuGet.
Install-Package Aspose.MedicalStep 2: Include Necessary Namespaces
Add references to the required namespaces in your controller.
using Aspose.Medical.Dicom;
using Aspose.Medical.Dicom.Serialization;
using Microsoft.AspNetCore.Mvc;Step 3: Create Async Deserialization Endpoint
Create an endpoint that deserializes JSON from the request body.
[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");
}Step 4: Create Async Serialization Endpoint
Create an endpoint that serializes DICOM to JSON in the response.
[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);
}Step 5: Handle Cancellation Tokens
Pass cancellation tokens for proper request cancellation handling.
[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();
}Complete ASP.NET Core Controller Example
Here is a complete controller implementing async DICOM JSON operations:
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}");
}
}
}Configuring Request Size Limits
For large DICOM files, configure request limits 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();Stream Processing Example
Process DICOM files without loading entirely into memory:
[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
);
}Error Handling Best Practices
Implement comprehensive error handling:
[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 });
}
}Additional Best Practices
Using Statements for Streams
Always use proper disposal patterns:
using (FileStream fs = System.IO.File.OpenRead(filepath))
{
// Process stream
}Timeout Configuration
Configure appropriate timeouts for long operations:
builder.WebHost.ConfigureKestrel(options =>
{
options.Limits.RequestHeadersTimeout = TimeSpan.FromMinutes(2);
options.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(5);
});Additional Information
- Async methods improve scalability but don’t necessarily speed up individual requests.
- Use cancellation tokens to properly handle client disconnections.
- Monitor memory usage when processing large DICOM files.
Conclusion
This tutorial has demonstrated how to implement async DICOM JSON serialization in ASP.NET Core web APIs using Aspose.Medical. Async operations are essential for building scalable healthcare APIs that handle large medical imaging data efficiently.