European ASP.NET MVC 4 and MVC 5 Hosting

BLOG about ASP.NET MVC 3, ASP.NET MVC 4, and ASP.NET MVC 5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

ASP.NET MVC Hosting - HostForLIFE.eu :: Transactional Outbox Pattern in ASP.NET Core MVC Using BackgroundService and EF Core Interceptors

clock November 23, 2026 13:43 by author Peter

Two different failure modes appear when an ASP.NET Core MVC action publishes a domain event or webhook to a message broker after saving business state to a relational database:

  • Database commits, broker publish fails (network blip, broker restart, timeout): Your database records the state change, but downstream consumers never receive the event—causing silent data drift.
  • Broker publish succeeds before or outside the transaction, database rolls back (constraint violation, deadlock, validation failure): Downstream consumers react to an event for data that does not exist.

The Transactional Outbox Pattern eliminates dual-write inconsistency by persisting outbox messages inside the exact same database transaction as your domain changes. An EF Core SaveChangesInterceptor harvests domain events raised on tracked entities right before SaveChangesAsync commits, writes OutboxMessage rows into the same transaction, and a BackgroundService backed by a bounded Channel<T> (plus periodic polling for crash recovery) dispatches pending messages reliably with retry/backoff and idempotent consumer handling.

1. Architectural Blueprint & Delivery Flow

[MVC Controller Action]
   │  raises domain event on aggregate entity
   ▼
[AppDbContext.SaveChangesAsync()]
   │  triggers SaveChangesInterceptor.SavingChangesAsync()
   ▼
[OutboxSaveChangesInterceptor]
   │  collects domain events from ChangeTracker
   │  serializes & adds OutboxMessage rows to same DbContext transaction
   ▼
[Database COMMIT] ──(atomic: domain row + outbox row commit together)
   │
   ├─> signals ChannelWriter<Guid> (fast wake-up path)
   │
   ▼
[OutboxDispatcherBackgroundService]
   ├─ drains ChannelReader<Guid> + periodic fallback poll (catches un-notified rows after restart)
   ├─ claims batch with row-level lock / atomic status transition
   ├─ publishes via IOutboxMessagePublisher (broker / event bus)
   └─ marks ProcessedAtUtc or increments RetryCount + NextAttemptAtUtc with backoff

Component

Responsibility

Failure & Recovery Behavior

Domain Entity (AggregateRoot)

Records domain events during state transitions without knowing about EF Core or brokers.

Cleared once harvested by the interceptor.

OutboxSaveChangesInterceptor

Extracts uncommitted domain events and inserts OutboxMessage rows into the active transaction.

Rolls back automatically if the database transaction fails.

Channel<Guid> + BackgroundService

Provides near-real-time dispatch while a periodic sweep catches missed/retryable rows.

Bounded channel with DropOldest or Wait wake-up signal; DB remains the source of truth.

Outbox Worker Retry Policy

Retries transient broker errors with exponential backoff; isolates poison messages after max attempts.

Never drops unacknowledged messages silently; logs failure details and Error text.

2. Domain Model, Outbox Entity, and EF Core Configuration

Let's model a clean aggregate (Invoice), an IDomainEvent contract, and an OutboxMessage entity persisted in the same AppDbContext.

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

public interface IDomainEvent
{
    Guid EventId { get; }
    DateTimeOffset OccurredAtUtc { get; }
}

public sealed record InvoiceIssuedDomainEvent(
    Guid EventId,
    Guid InvoiceId,
    string InvoiceNumber,
    decimal GrossAmount,
    DateTimeOffset OccurredAtUtc
) : IDomainEvent;

public abstract class Entity
{
    private readonly List<IDomainEvent> _domainEvents = [];

    public IReadOnlyCollection<IDomainEvent> DomainEvents => _domainEvents.AsReadOnly();

    protected void RaiseDomainEvent(IDomainEvent domainEvent)
    {
        _domainEvents.Add(domainEvent);
    }

    public void ClearDomainEvents()
    {
        _domainEvents.Clear();
    }
}

public sealed class Invoice : Entity
{
    public Guid Id { get; private set; }
    public string InvoiceNumber { get; private set; } = string.Empty;
    public decimal GrossAmount { get; private set; }
    public string Status { get; private set; } = "Draft";
    public DateTimeOffset CreatedAtUtc { get; private set; }

    private Invoice() { }

    public static Invoice Issue(string invoiceNumber, decimal grossAmount, DateTimeOffset nowUtc)
    {
        if (string.IsNullOrWhiteSpace(invoiceNumber))
        {
            throw new ArgumentException("Invoice number is required.", nameof(invoiceNumber));
        }

        if (grossAmount <= 0m)
        {
            throw new ArgumentOutOfRangeException(nameof(grossAmount), "Gross amount must be positive.");
        }

        var invoice = new Invoice
        {
            Id = Guid.NewGuid(),
            InvoiceNumber = invoiceNumber.Trim().ToUpperInvariant(),
            GrossAmount = decimal.Round(grossAmount, 2, MidpointRounding.AwayFromZero),
            Status = "Issued",
            CreatedAtUtc = nowUtc
        };

        invoice.RaiseDomainEvent(new InvoiceIssuedDomainEvent(
            EventId: Guid.NewGuid(),
            InvoiceId: invoice.Id,
            InvoiceNumber: invoice.InvoiceNumber,
            GrossAmount: invoice.GrossAmount,
            OccurredAtUtc: nowUtc));

        return invoice;
    }
}

public sealed class OutboxMessage
{
    public Guid Id { get; set; }
    public string EventType { get; set; } = string.Empty;
    public string PayloadJson { get; set; } = string.Empty;
    public DateTimeOffset OccurredAtUtc { get; set; }
    public DateTimeOffset? ProcessedAtUtc { get; set; }
    public DateTimeOffset NextAttemptAtUtc { get; set; }
    public int RetryCount { get; set; }
    public string? LastError { get; set; }
}

public sealed class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options)
        : base(options)
    {
    }

    public DbSet<Invoice> Invoices => Set<Invoice>();
    public DbSet<OutboxMessage> OutboxMessages => Set<OutboxMessage>();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Invoice>(builder =>
        {
            builder.HasKey(x => x.Id);
            builder.Property(x => x.InvoiceNumber).HasMaxLength(40).IsRequired();
            builder.HasIndex(x => x.InvoiceNumber).IsUnique();
            builder.Property(x => x.GrossAmount).HasColumnType("decimal(18,2)");
            builder.Property(x => x.Status).HasMaxLength(24).IsRequired();
        });

        modelBuilder.Entity<OutboxMessage>(builder =>
        {
            builder.HasKey(x => x.Id);
            builder.Property(x => x.EventType).HasMaxLength(256).IsRequired();
            builder.Property(x => x.PayloadJson).IsRequired();
            builder.Property(x => x.LastError).HasMaxLength(2000);

            // Supports fast polling of unprocessed messages eligible for retry
            builder.HasIndex(x => new { x.ProcessedAtUtc, x.NextAttemptAtUtc, x.OccurredAtUtc });
        });
    }
}


3. EF Core SaveChangesInterceptor & Wake-Up Signaler
OutboxSaveChangesInterceptor hooks into SavingChangesAsync before EF Core flushes changes to the database. Any OutboxMessage entities added here become part of the exact same DbContext transaction as the Invoice insert or update.
using System.Text.Json;
using System.Threading.Channels;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;

public sealed class OutboxNotificationQueue
{
    private readonly Channel<Guid> _channel;

    public OutboxNotificationQueue(int capacity = 4096)
    {
        var options = new BoundedChannelOptions(capacity)
        {
            FullMode = BoundedChannelFullMode.DropOldest,
            SingleReader = true,
            SingleWriter = false
        };
        _channel = Channel.CreateBounded<Guid>(options);
    }

    public ChannelReader<Guid> Reader => _channel.Reader;

    public void TryNotify(Guid outboxMessageId)
    {
        _channel.Writer.TryWrite(outboxMessageId);
    }
}

public sealed class OutboxSaveChangesInterceptor : SaveChangesInterceptor
{
    private static readonly JsonSerializerOptions SerializerOptions = new(JsonSerializerDefaults.Web);
    private readonly OutboxNotificationQueue _notificationQueue;

    public OutboxSaveChangesInterceptor(OutboxNotificationQueue notificationQueue)
    {
        _notificationQueue = notificationQueue;
    }

    public override ValueTask<InterceptionResult<int>> SavingChangesAsync(
        DbContextEventData eventData,
        InterceptionResult<int> result,
        CancellationToken cancellationToken = default)
    {
        if (eventData.Context is not null)
        {
            AppendOutboxMessages(eventData.Context);
        }

        return ValueTask.FromResult(result);
    }

    private void AppendOutboxMessages(DbContext dbContext)
    {
        var entitiesWithEvents = dbContext.ChangeTracker
            .Entries<Entity>()
            .Where(e => e.Entity.DomainEvents.Count > 0)
            .Select(e => e.Entity)
            .ToList();

        if (entitiesWithEvents.Count == 0)
        {
            return;
        }

        DateTimeOffset nowUtc = DateTimeOffset.UtcNow;
        var outboxEntries = new List<OutboxMessage>();

        foreach (Entity entity in entitiesWithEvents)
        {
            foreach (IDomainEvent domainEvent in entity.DomainEvents)
            {
                Type eventClrType = domainEvent.GetType();
                string payloadJson = JsonSerializer.Serialize(domainEvent, eventClrType, SerializerOptions);

                outboxEntries.Add(new OutboxMessage
                {
                    Id = domainEvent.EventId == Guid.Empty ? Guid.NewGuid() : domainEvent.EventId,
                    EventType = eventClrType.AssemblyQualifiedName ?? eventClrType.FullName ?? eventClrType.Name,
                    PayloadJson = payloadJson,
                    OccurredAtUtc = domainEvent.OccurredAtUtc == default ? nowUtc : domainEvent.OccurredAtUtc,
                    NextAttemptAtUtc = nowUtc,
                    RetryCount = 0
                });
            }

            entity.ClearDomainEvents();
        }

        dbContext.Set<OutboxMessage>().AddRange(outboxEntries);

        foreach (OutboxMessage msg in outboxEntries)
        {
            _notificationQueue.TryNotify(msg.Id);
        }
    }
}


4. Publisher Abstraction and BackgroundService Dispatcher

Decoupling message transport behind IOutboxMessagePublisher allows you to publish to RabbitMQ, MassTransit, Azure Service Bus, Kafka, or an internal event bus while keeping retry, backoff, and poison-message isolation centralized in the BackgroundService.

using Microsoft.EntityFrameworkCore;

public interface IOutboxMessagePublisher
{
    Task PublishAsync(OutboxMessage message, CancellationToken cancellationToken = default);
}

public sealed class LoggingBrokerOutboxPublisher : IOutboxMessagePublisher
{
    private readonly ILogger<LoggingBrokerOutboxPublisher> _logger;

    public LoggingBrokerOutboxPublisher(ILogger<LoggingBrokerOutboxPublisher> logger)
    {
        _logger = logger;
    }

    public Task PublishAsync(OutboxMessage message, CancellationToken cancellationToken = default)
    {
        // Replace with your real broker/bus producer (e.g., MassTransit IPublishEndpoint, RabbitMQ channel, Service Bus sender)
        _logger.LogInformation(
            "Published outbox message {OutboxId} of type {EventType} (Retry: {RetryCount}).",
            message.Id,
            message.EventType,
            message.RetryCount);

        return Task.CompletedTask;
    }
}

public sealed class OutboxDispatcherBackgroundService : BackgroundService
{
    private const int BatchSize = 50;
    private const int MaxRetries = 5;
    private static readonly TimeSpan FallbackPollInterval = TimeSpan.FromSeconds(10);

    private readonly IServiceScopeFactory _scopeFactory;
    private readonly OutboxNotificationQueue _notificationQueue;
    private readonly ILogger<OutboxDispatcherBackgroundService> _logger;

    public OutboxDispatcherBackgroundService(
        IServiceScopeFactory scopeFactory,
        OutboxNotificationQueue notificationQueue,
        ILogger<OutboxDispatcherBackgroundService> logger)
    {
        _scopeFactory = scopeFactory;
        _notificationQueue = notificationQueue;
        _logger = logger;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        _logger.LogInformation("Outbox dispatcher started.");

        // Drain any backlog immediately on startup
        await ProcessPendingBatchAsync(stoppingToken);

        while (!stoppingToken.IsCancellationRequested)
        {
            try
            {
                using var delayCts = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken);
                delayCts.CancelAfter(FallbackPollInterval);

                try
                {
                    await _notificationQueue.Reader.WaitToReadAsync(delayCts.Token);
                    // Drain queued wake-up signals
                    while (_notificationQueue.Reader.TryRead(out _))
                    {
                    }
                }
                catch (OperationCanceledException) when (!stoppingToken.IsCancellationRequested)
                {
                    // Fallback timer elapsed; sweep DB for pending or retryable messages
                }

                await ProcessPendingBatchAsync(stoppingToken);
            }
            catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
            {
                break;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Unexpected error in outbox dispatcher loop; backing off briefly.");
                await Task.Delay(TimeSpan.FromSeconds(2), stoppingToken);
            }
        }

        _logger.LogInformation("Outbox dispatcher stopped.");
    }

    private async Task ProcessPendingBatchAsync(CancellationToken cancellationToken)
    {
        using IServiceScope scope = _scopeFactory.CreateScope();
        var dbContext = scope.ServiceProvider.GetRequiredService<AppDbContext>();
        var publisher = scope.ServiceProvider.GetRequiredService<IOutboxMessagePublisher>();

        DateTimeOffset nowUtc = DateTimeOffset.UtcNow;

        List<OutboxMessage> batch = await dbContext.OutboxMessages
            .Where(m => m.ProcessedAtUtc == null &&
                        m.RetryCount < MaxRetries &&
                        m.NextAttemptAtUtc <= nowUtc)
            .OrderBy(m => m.OccurredAtUtc)
            .Take(BatchSize)
            .ToListAsync(cancellationToken);

        if (batch.Count == 0)
        {
            return;
        }

        foreach (OutboxMessage message in batch)
        {
            cancellationToken.ThrowIfCancellationRequested();

            try
            {
                await publisher.PublishAsync(message, cancellationToken);

                message.ProcessedAtUtc = DateTimeOffset.UtcNow;
                message.LastError = null;
            }
            catch (Exception ex) when (!cancellationToken.IsCancellationRequested)
            {
                message.RetryCount += 1;
                string errorText = ex.Message.Length > 1900 ? ex.Message[..1900] : ex.Message;
                message.LastError = errorText;

                double backoffSeconds = Math.Min(300, Math.Pow(2, message.RetryCount) * 5);
                message.NextAttemptAtUtc = DateTimeOffset.UtcNow.AddSeconds(backoffSeconds);

                _logger.LogWarning(
                    ex,
                    "Failed publishing outbox message {OutboxId} on attempt {RetryCount}/{MaxRetries}; next attempt at {NextAttemptAtUtc}.",
                    message.Id,
                    message.RetryCount,
                    MaxRetries,
                    message.NextAttemptAtUtc);
            }
        }

        await dbContext.SaveChangesAsync(cancellationToken);
    }
}


5. Wiring into Program.cs and MVC Controller
Service & Hosted Worker Registration (Program.cs)

Register OutboxSaveChangesInterceptor as a singleton or scoped service and attach it to AddDbContext via AddInterceptors(...).
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddSingleton<OutboxNotificationQueue>();
builder.Services.AddSingleton<OutboxSaveChangesInterceptor>();
builder.Services.AddSingleton<IOutboxMessagePublisher, LoggingBrokerOutboxPublisher>();

builder.Services.AddDbContext<AppDbContext>((sp, options) =>
{
    var interceptor = sp.GetRequiredService<OutboxSaveChangesInterceptor>();
    string connectionString = builder.Configuration.GetConnectionString("DefaultConnection")
        ?? throw new InvalidOperationException("Missing DefaultConnection string.");

    options.UseSqlServer(connectionString)
           .AddInterceptors(interceptor);
});

builder.Services.AddHostedService<OutboxDispatcherBackgroundService>();
builder.Services.AddControllersWithViews();

var app = builder.Build();

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.MapControllers();

app.Run();

public partial class Program { }


MVC Controller Action (InvoicesController.cs)
The controller stays focused on issuing the Invoice and calling SaveChangesAsync(). Both the Invoice row and the OutboxMessage row commit atomically in one transaction.
using Microsoft.AspNetCore.Mvc;

public sealed record IssueInvoiceRequest(
    string InvoiceNumber,
    decimal GrossAmount
);

public sealed record IssueInvoiceResponse(
    Guid InvoiceId,
    string InvoiceNumber,
    decimal GrossAmount,
    string Status
);

[ApiController]
[Route("api/invoices")]
public sealed class InvoicesController : ControllerBase
{
    private readonly AppDbContext _dbContext;

    public InvoicesController(AppDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    [HttpPost]
    public async Task<IActionResult> Issue(
        [FromBody] IssueInvoiceRequest request,
        CancellationToken cancellationToken)
    {
        try
        {
            Invoice invoice = Invoice.Issue(
                request.InvoiceNumber,
                request.GrossAmount,
                DateTimeOffset.UtcNow);

            _dbContext.Invoices.Add(invoice);
            await _dbContext.SaveChangesAsync(cancellationToken);

            var response = new IssueInvoiceResponse(
                invoice.Id,
                invoice.InvoiceNumber,
                invoice.GrossAmount,
                invoice.Status);

            return CreatedAtAction(nameof(GetById), new { id = invoice.Id }, response);
        }
        catch (ArgumentException ex)
        {
            return BadRequest(new ProblemDetails
            {
                Title = "Invalid Invoice Input",
                Detail = ex.Message,
                Status = StatusCodes.Status400BadRequest
            });
        }
    }

    [HttpGet("{id:guid}")]
    public async Task<IActionResult> GetById(Guid id, CancellationToken cancellationToken)
    {
        var invoice = await _dbContext.Invoices
            .AsNoTracking()
            .Where(x => x.Id == id)
            .Select(x => new IssueInvoiceResponse(x.Id, x.InvoiceNumber, x.GrossAmount, x.Status))
            .FirstOrDefaultAsync(cancellationToken);

        return invoice is null ? NotFound() : Ok(invoice);
    }
}

6. End-to-End Integration Testing with WebApplicationFactory<Program>
Using an in-memory/SQLite/SQL Server AppDbContext in WebApplicationFactory<Program>, you can verify that issuing an invoice writes an OutboxMessage atomically and that the BackgroundService marks it processed without losing messages on failed attempts.
using System.Collections.Concurrent;
using System.Net;
using System.Net.Http.Json;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Xunit;

public sealed class RecordingOutboxPublisher : IOutboxMessagePublisher
{
    public ConcurrentBag<OutboxMessage> PublishedMessages { get; } = [];

    public Task PublishAsync(OutboxMessage message, CancellationToken cancellationToken = default)
    {
        PublishedMessages.Add(message);
        return Task.CompletedTask;
    }
}

public sealed class OutboxTestFactory : WebApplicationFactory<Program>, IAsyncLifetime
{
    private readonly SqliteConnection _connection = new("DataSource=:memory:");
    public RecordingOutboxPublisher RecordingPublisher { get; } = new();

    public async Task InitializeAsync()
    {
        await _connection.OpenAsync();

        using IServiceScope scope = Services.CreateScope();
        var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
        await db.Database.EnsureCreatedAsync();
    }

    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        builder.ConfigureServices(services =>
        {
            ServiceDescriptor? dbContextDescriptor = services.SingleOrDefault(
                d => d.ServiceType == typeof(DbContextOptions<AppDbContext>));
            if (dbContextDescriptor is not null)
            {
                services.Remove(dbContextDescriptor);
            }

            ServiceDescriptor? publisherDescriptor = services.SingleOrDefault(
                d => d.ServiceType == typeof(IOutboxMessagePublisher));
            if (publisherDescriptor is not null)
            {
                services.Remove(publisherDescriptor);
            }

            services.AddSingleton<IOutboxMessagePublisher>(RecordingPublisher);
            services.AddDbContext<AppDbContext>((sp, options) =>
            {
                var interceptor = sp.GetRequiredService<OutboxSaveChangesInterceptor>();
                options.UseSqlite(_connection)
                       .AddInterceptors(interceptor);
            });
        });
    }

    public new async Task DisposeAsync()
    {
        await base.DisposeAsync();
        await _connection.DisposeAsync();
    }
}

public sealed class TransactionalOutboxTests : IClassFixture<OutboxTestFactory>
{
    private readonly OutboxTestFactory _factory;

    public TransactionalOutboxTests(OutboxTestFactory factory)
    {
        _factory = factory;
    }

    [Fact]
    public async Task IssueInvoice_PersistsInvoiceAndDispatchesOutboxMessage()
    {
        using HttpClient client = _factory.CreateClient();
        string invNumber = $"INV-{Guid.NewGuid():N}"[..14];

        HttpResponseMessage response = await client.PostAsJsonAsync(
            "/api/invoices",
            new IssueInvoiceRequest(invNumber, 1250.00m));

        Assert.Equal(HttpStatusCode.Created, response.StatusCode);
        IssueInvoiceResponse? created = await response.Content.ReadFromJsonAsync<IssueInvoiceResponse>();
        Assert.NotNull(created);

        // Allow background dispatcher a brief window to process queued item
        await Task.Delay(TimeSpan.FromMilliseconds(350));

        using IServiceScope scope = _factory.Services.CreateScope();
        var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();

        OutboxMessage? outboxRow = await db.OutboxMessages
            .AsNoTracking()
            .FirstOrDefaultAsync(m => m.PayloadJson.Contains(created.InvoiceId.ToString()));

        Assert.NotNull(outboxRow);
        Assert.NotNull(outboxRow.ProcessedAtUtc);
        Assert.Contains(_factory.RecordingPublisher.PublishedMessages, m => m.Id == outboxRow.Id);
    }
}

7. Conclusion
The Transactional Outbox Pattern—implemented with an EF Core SaveChangesInterceptor and a BackgroundService backed by a Channel<T> wake-up queue and periodic database sweep—gives ASP.NET Core MVC applications reliable, at-least-once event publication without dual-write race conditions. Domain state and outbox messages commit inside one database transaction, transient broker failures back off and retry automatically, and downstream consumers can safely deduplicate by OutboxMessage.Id / EventId.



ASP.NET MVC Hosting - HostForLIFE.eu :: End-to-End Masterclass: Using Span<T>, PipeReader, and Custom InputFormatter in ASP.NET Core MVC to Optimise Zero-Allocation Performance

clock November 20, 2026 12:56 by author Peter

When ASP.NET Core MVC endpoints process high-frequency webhooks, telemetry batches, or custom delimited payloads, default deserialisation pipelines can become a major source of memory churn. Reading an entire request stream into a string or byte[] array, splitting substrings with string.Split, and parsing individual tokens with int.Parse(string) or decimal.Parse(string) allocating heap objects on every request. Under heavy load, those short-lived allocations pressure the Garbage Collector (GC), trigger Gen0/Gen1/Gen2 collections, and spike tail (p99) latency.

By combining System.IO.Pipelines (PipeReader), ReadOnlySpan<byte> / ReadOnlySequence<byte>, and a custom TextInputFormatter / InputFormatter, you can stream incoming request bytes directly from Kestrel and parse structured records with minimal or zero heap allocations per record. This guide walks through how to design, implement, register, and benchmark a zero-allocation custom input formatter in ASP.NET Core MVC.

1. Architectural Blueprint & Allocation Hotspots
Understanding where allocations happen in standard request ingestion helps explain why PipeReader and Span<T> are so effective:

Stage

Naive Stream/String Approach

Zero-Allocation PipeReader + Span<byte> Approach

Stream Reading

StreamReader.ReadToEndAsync() buffers the entire body into a large string on the heap.

HttpContext.Request.BodyReader (PipeReader) yields ReadOnlySequence<byte> chunks as network buffers arrive.

Tokenization

`line.Split('

')allocates astring[]plus astring` instance for every field.

Type Parsing

decimal.Parse(fieldStr) requires a string and culture-heavy overhead.

Utf8Parser.TryParse(fieldSpan, out decimal value, out _) parses ASCII/UTF-8 digits straight from bytes.

HTTP Request Body (Kestrel Socket / Pipe)
   │
   ▼
[PipeReader (HttpContext.Request.BodyReader)]
   │  Reads ReadOnlySequence<byte> segments without copying entire payload
   ▼
[Custom InputFormatter (TelemetryBatchInputFormatter)]
   │  Handles single-segment Span<byte> fast path + multi-segment SequenceReader fallback
   │  Parses fields with Utf8Parser.TryParse (zero string allocations)
   ▼
[Strongly Typed Domain Model (TelemetryBatch)]
   │
   ▼
[MVC Controller Action]


2. Target Domain Model & Wire Format
Suppose an ingestion endpoint receives high-throughput metering or telemetry batches formatted as newline-delimited pipe records (|-separated):

METER-1001|1732000800|148.75|200
METER-1002|1732000801|312.40|200


Each line contains:

  • DeviceCode (ASCII string)
  • UnixTimestampSeconds (long)
  • ReadingValue (decimal)
  • StatusCode (int)

We define the immutable domain model and batch container:
public readonly record struct TelemetryReading(
    string DeviceCode,
    long UnixTimestampSeconds,
    decimal ReadingValue,
    int StatusCode
);

public sealed class TelemetryBatch
{
    public List<TelemetryReading> Readings { get; } = [];
}

3. Implementing the Zero-Allocation Custom InputFormatter
When reading from PipeReader, a single line or field can occasionally straddle two ReadOnlyMemory<byte> segments inside a ReadOnlySequence<byte>. A production-grade formatter handles contiguous single-segment buffers on a fast path using ReadOnlySpan<byte> and Utf8Parser, while falling back to SequenceReader<byte> when a line spans multiple segments.
using System.Buffers;
using System.Buffers.Text;
using System.IO.Pipelines;
using System.Text;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.Net.Http.Headers;

public sealed class TelemetryBatchInputFormatter : InputFormatter
{
    private const byte PipeByte = (byte)'|';
    private const byte NewLineByte = (byte)'\n';
    private const byte CarriageReturnByte = (byte)'\r';
    private const int MaxBatchReadings = 10_000;

    public TelemetryBatchInputFormatter()
    {
        SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("text/x-telemetry-batch"));
    }

    protected override bool CanReadType(Type type)
    {
        return type == typeof(TelemetryBatch);
    }

    public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context)
    {
        ArgumentNullException.ThrowIfNull(context);

        var httpContext = context.HttpContext;
        var reader = httpContext.Request.BodyReader;
        var batch = new TelemetryBatch();
        int lineNumber = 0;

        try
        {
            while (true)
            {
                ReadResult result = await reader.ReadAsync(httpContext.RequestAborted);
                ReadOnlySequence<byte> buffer = result.Buffer;

                while (TryReadLine(ref buffer, out ReadOnlySequence<byte> lineSequence))
                {
                    lineNumber++;

                    if (batch.Readings.Count >= MaxBatchReadings)
                    {
                        context.ModelState.TryAddModelError(
                            context.ModelName,
                            $"Batch exceeds maximum allowed size of {MaxBatchReadings} readings.");
                        reader.AdvanceTo(buffer.End);
                        return await InputFormatterResult.FailureAsync();
                    }

                    if (!TryParseLine(lineSequence, out TelemetryReading reading, out string? error))
                    {
                        context.ModelState.TryAddModelError(
                            context.ModelName,
                            $"Line {lineNumber}: {error ?? "Invalid telemetry record format."}");
                        reader.AdvanceTo(buffer.End);
                        return await InputFormatterResult.FailureAsync();
                    }

                    batch.Readings.Add(reading);
                }

                // Tell the PipeReader how much of the buffer was consumed and examined
                reader.AdvanceTo(buffer.Start, buffer.End);

                if (result.IsCompleted)
                {
                    // Handle trailing data if the final line did not end with '\n'
                    if (!buffer.IsEmpty)
                    {
                        lineNumber++;
                        if (!TryParseLine(buffer, out TelemetryReading trailingReading, out string? error))
                        {
                            context.ModelState.TryAddModelError(
                                context.ModelName,
                                $"Line {lineNumber}: {error ?? "Invalid trailing telemetry record."}");
                            return await InputFormatterResult.FailureAsync();
                        }

                        batch.Readings.Add(trailingReading);
                        reader.AdvanceTo(buffer.End);
                    }

                    break;
                }
            }

            return await InputFormatterResult.SuccessAsync(batch);
        }
        catch (OperationCanceledException)
        {
            throw;
        }
        catch (Exception ex)
        {
            context.ModelState.TryAddModelError(
                context.ModelName,
                $"Error reading telemetry stream: {ex.Message}");
            return await InputFormatterResult.FailureAsync();
        }
    }

    private static bool TryReadLine(ref ReadOnlySequence<byte> buffer, out ReadOnlySequence<byte> line)
    {
        SequencePosition? position = buffer.PositionOf(NewLineByte);
        if (position is null)
        {
            line = default;
            return false;
        }

        line = buffer.Slice(0, position.Value);
        buffer = buffer.Slice(buffer.GetPosition(1, position.Value));
        return true;
    }

    private static bool TryParseLine(
        ReadOnlySequence<byte> line,
        out TelemetryReading reading,
        out string? error)
    {
        reading = default;
        error = null;

        // Fast path: entire line fits inside a single contiguous memory span
        if (line.IsSingleSegment)
        {
            return TryParseSpan(line.FirstSpan, out reading, out error);
        }

        // Fallback path for lines split across PipeReader segments
        var seqReader = new SequenceReader<byte>(line);
        if (!seqReader.TryReadTo(out ReadOnlySequence<byte> deviceSeq, PipeByte, advancePastDelimiter: true) ||
            !seqReader.TryReadTo(out ReadOnlySequence<byte> timestampSeq, PipeByte, advancePastDelimiter: true) ||
            !seqReader.TryReadTo(out ReadOnlySequence<byte> valueSeq, PipeByte, advancePastDelimiter: true))
        {
            error = "Expected 4 pipe-delimited fields.";
            return false;
        }

        ReadOnlySequence<byte> statusSeq = line.Slice(seqReader.Position);
        if (statusSeq.IsEmpty)
        {
            error = "Missing status code field.";
            return false;
        }

        string deviceCode = Encoding.ASCII.GetString(deviceSeq);
        if (string.IsNullOrWhiteSpace(deviceCode))
        {
            error = "Device code cannot be empty.";
            return false;
        }

        if (!TryParseInt64(timestampSeq, out long timestamp) ||
            !TryParseDecimal(valueSeq, out decimal value) ||
            !TryParseInt32(statusSeq, out int statusCode))
        {
            error = "One or more numeric fields could not be parsed.";
            return false;
        }

        reading = new TelemetryReading(deviceCode, timestamp, value, statusCode);
        return true;
    }

    private static bool TryParseSpan(
        ReadOnlySpan<byte> span,
        out TelemetryReading reading,
        out string? error)
    {
        reading = default;
        error = null;

        // Trim optional trailing '\r' from CRLF payloads
        if (!span.IsEmpty && span[^1] == CarriageReturnByte)
        {
            span = span[..^1];
        }

        if (span.IsEmpty)
        {
            error = "Empty telemetry line.";
            return false;
        }

        int idx1 = span.IndexOf(PipeByte);
        if (idx1 <= 0)
        {
            error = "Missing or invalid device code.";
            return false;
        }

        ReadOnlySpan<byte> deviceSpan = span[..idx1];
        ReadOnlySpan<byte> rest1 = span[(idx1 + 1)..];

        int idx2 = rest1.IndexOf(PipeByte);
        if (idx2 <= 0)
        {
            error = "Missing or invalid timestamp field.";
            return false;
        }

        ReadOnlySpan<byte> timestampSpan = rest1[..idx2];
        ReadOnlySpan<byte> rest2 = rest1[(idx2 + 1)..];

        int idx3 = rest2.IndexOf(PipeByte);
        if (idx3 <= 0)
        {
            error = "Missing or invalid reading value field.";
            return false;
        }

        ReadOnlySpan<byte> valueSpan = rest2[..idx3];
        ReadOnlySpan<byte> statusSpan = rest2[(idx3 + 1)..];

        if (statusSpan.IsEmpty)
        {
            error = "Missing status code field.";
            return false;
        }

        if (!Utf8Parser.TryParse(timestampSpan, out long timestamp, out int tsConsumed, 'D') ||
            tsConsumed != timestampSpan.Length)
        {
            error = "Invalid integer timestamp.";
            return false;
        }

        if (!Utf8Parser.TryParse(valueSpan, out decimal value, out int valConsumed) ||
            valConsumed != valueSpan.Length)
        {
            error = "Invalid decimal reading value.";
            return false;
        }

        if (!Utf8Parser.TryParse(statusSpan, out int statusCode, out int statusConsumed, 'D') ||
            statusConsumed != statusSpan.Length)
        {
            error = "Invalid integer status code.";
            return false;
        }

        string deviceCode = Encoding.ASCII.GetString(deviceSpan);
        reading = new TelemetryReading(deviceCode, timestamp, value, statusCode);
        return true;
    }

    private static bool TryParseInt64(ReadOnlySequence<byte> seq, out long value)
    {
        if (seq.IsSingleSegment)
        {
            return Utf8Parser.TryParse(seq.FirstSpan, out value, out int consumed, 'D') &&
                   consumed == seq.FirstSpan.Length;
        }

        Span<byte> stackBuf = stackalloc byte[32];
        if (seq.Length > stackBuf.Length)
        {
            value = 0;
            return false;
        }

        seq.CopyTo(stackBuf);
        return Utf8Parser.TryParse(stackBuf[..(int)seq.Length], out value, out int consumed, 'D') &&
               consumed == seq.Length;
    }

    private static bool TryParseDecimal(ReadOnlySequence<byte> seq, out decimal value)
    {
        if (seq.IsSingleSegment)
        {
            return Utf8Parser.TryParse(seq.FirstSpan, out value, out int consumed) &&
                   consumed == seq.FirstSpan.Length;
        }

        Span<byte> stackBuf = stackalloc byte[64];
        if (seq.Length > stackBuf.Length)
        {
            value = 0;
            return false;
        }

        seq.CopyTo(stackBuf);
        return Utf8Parser.TryParse(stackBuf[..(int)seq.Length], out value, out int consumed) &&
               consumed == seq.Length;
    }

    private static bool TryParseInt32(ReadOnlySequence<byte> seq, out int value)
    {
        if (seq.IsSingleSegment)
        {
            return Utf8Parser.TryParse(seq.FirstSpan, out value, out int consumed, 'D') &&
                   consumed == seq.FirstSpan.Length;
        }

        Span<byte> stackBuf = stackalloc byte[16];
        if (seq.Length > stackBuf.Length)
        {
            value = 0;
            return false;
        }

        seq.CopyTo(stackBuf);
        return Utf8Parser.TryParse(stackBuf[..(int)seq.Length], out value, out int consumed, 'D') &&
               consumed == seq.Length;
    }
}


4. Registering the Formatter & Consuming It in an MVC Controller
Programmatic Registration (Program.cs)

Insert TelemetryBatchInputFormatter into MvcOptions.InputFormatters so MVC invokes it automatically when a request carries Content-Type: text/x-telemetry-batch and targets TelemetryBatch.
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers(options =>
{
    options.InputFormatters.Insert(0, new TelemetryBatchInputFormatter());
});

var app = builder.Build();
app.MapControllers();
app.Run();


Controller Action (TelemetryController.cs)
The controller action receives a validated TelemetryBatch without ever touching raw streams, StreamReader, or string splitting logic:

using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/telemetry")]
public sealed class TelemetryController : ControllerBase
{
    private readonly ILogger<TelemetryController> _logger;

    public TelemetryController(ILogger<TelemetryController> logger)
    {
        _logger = logger;
    }

    [HttpPost("ingest")]
    [Consumes("text/x-telemetry-batch")]
    public IActionResult Ingest([FromBody] TelemetryBatch batch)
    {
        if (!ModelState.IsValid)
        {
            return ValidationProblem(ModelState);
        }

        decimal totalReading = 0m;
        foreach (var reading in batch.Readings)
        {
            totalReading += reading.ReadingValue;
        }

        _logger.LogInformation(
            "Ingested {Count} telemetry readings with total value {Total}.",
            batch.Readings.Count,
            totalReading);

        return Ok(new
        {
            AcceptedCount = batch.Readings.Count,
            TotalReadingValue = totalReading
        });
    }
}

5. Verifying Behavior and Allocation Profile
You can verify both correctness and allocation behavior using integration tests with WebApplicationFactory<Program> and microbenchmarks with BenchmarkDotNet:
using System.Net;
using System.Net.Http.Headers;
using System.Text;
using Microsoft.AspNetCore.Mvc.Testing;
using Xunit;

public sealed class TelemetryControllerTests : IClassFixture<WebApplicationFactory<Program>>
{
    private readonly WebApplicationFactory<Program> _factory;

    public TelemetryControllerTests(WebApplicationFactory<Program> factory)
    {
        _factory = factory;
    }

    [Fact]
    public async Task Ingest_ValidPipeDelimitedBatch_ReturnsAcceptedSummary()
    {
        using var client = _factory.CreateClient();
        const string payload = "MTR-01|1732000800|125.50|200\nMTR-02|1732000805|74.50|200\n";

        using var content = new StringContent(payload, Encoding.ASCII);
        content.Headers.ContentType = new MediaTypeHeaderValue("text/x-telemetry-batch");

        var response = await client.PostAsync("/api/telemetry/ingest", content);

        Assert.Equal(HttpStatusCode.OK, response.StatusCode);
    }

    [Fact]
    public async Task Ingest_MalformedNumericField_ReturnsValidationProblem()
    {
        using var client = _factory.CreateClient();
        const string payload = "MTR-01|NOT_A_TIMESTAMP|125.50|200\n";

        using var content = new StringContent(payload, Encoding.ASCII);
        content.Headers.ContentType = new MediaTypeHeaderValue("text/x-telemetry-batch");

        var response = await client.PostAsync("/api/telemetry/ingest", content);

        Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
    }
}

When benchmarking TelemetryBatchInputFormatter with BenchmarkDotNet ([MemoryDiagnoser]), keep two practical rules in mind:
Test both single-segment and multi-segment ReadOnlySequence<byte> inputs: A real network pipe often splits payloads across segments, so verify that your SequenceReader<byte> fallback produces identical results to the contiguous ReadOnlySpan<byte> fast path.

Guard against untrusted input sizes: Always enforce explicit line/batch limits (MaxBatchReadings) and validate Utf8Parser consumed byte counts (consumed == span.Length) so trailing garbage characters cannot slip past partial parses.

Conclusion
Pairing PipeReader, ReadOnlySpan<byte> / Utf8Parser, and a custom InputFormatter gives ASP.NET Core MVC applications a clean, high-throughput path for ingesting custom or high-volume payloads. Instead of buffering full request bodies into strings and allocating intermediate arrays per line, your application streams bytes directly from the network pipeline, validates malformed records early via ModelState, and hands clean domain models to your controllers with drastically lower GC pressure and tighter tail latency.



ASP.NET MVC Hosting - HostForLIFE.eu :: End-to-End Masterclass: Using Span<T>, PipeReader, and Custom InputFormatter in ASP.NET Core MVC to Optimise Zero-Allocation Performance

clock November 20, 2026 12:56 by author Peter

When ASP.NET Core MVC endpoints process high-frequency webhooks, telemetry batches, or custom delimited payloads, default deserialisation pipelines can become a major source of memory churn. Reading an entire request stream into a string or byte[] array, splitting substrings with string.Split, and parsing individual tokens with int.Parse(string) or decimal.Parse(string) allocating heap objects on every request. Under heavy load, those short-lived allocations pressure the Garbage Collector (GC), trigger Gen0/Gen1/Gen2 collections, and spike tail (p99) latency.

By combining System.IO.Pipelines (PipeReader), ReadOnlySpan<byte> / ReadOnlySequence<byte>, and a custom TextInputFormatter / InputFormatter, you can stream incoming request bytes directly from Kestrel and parse structured records with minimal or zero heap allocations per record. This guide walks through how to design, implement, register, and benchmark a zero-allocation custom input formatter in ASP.NET Core MVC.

1. Architectural Blueprint & Allocation Hotspots
Understanding where allocations happen in standard request ingestion helps explain why PipeReader and Span<T> are so effective:

Stage

Naive Stream/String Approach

Zero-Allocation PipeReader + Span<byte> Approach

Stream Reading

StreamReader.ReadToEndAsync() buffers the entire body into a large string on the heap.

HttpContext.Request.BodyReader (PipeReader) yields ReadOnlySequence<byte> chunks as network buffers arrive.

Tokenization

`line.Split('

')allocates astring[]plus astring` instance for every field.

Type Parsing

decimal.Parse(fieldStr) requires a string and culture-heavy overhead.

Utf8Parser.TryParse(fieldSpan, out decimal value, out _) parses ASCII/UTF-8 digits straight from bytes.

HTTP Request Body (Kestrel Socket / Pipe)
   │
   ▼
[PipeReader (HttpContext.Request.BodyReader)]
   │  Reads ReadOnlySequence<byte> segments without copying entire payload
   ▼
[Custom InputFormatter (TelemetryBatchInputFormatter)]
   │  Handles single-segment Span<byte> fast path + multi-segment SequenceReader fallback
   │  Parses fields with Utf8Parser.TryParse (zero string allocations)
   ▼
[Strongly Typed Domain Model (TelemetryBatch)]
   │
   ▼
[MVC Controller Action]


2. Target Domain Model & Wire Format
Suppose an ingestion endpoint receives high-throughput metering or telemetry batches formatted as newline-delimited pipe records (|-separated):

METER-1001|1732000800|148.75|200
METER-1002|1732000801|312.40|200


Each line contains:

  • DeviceCode (ASCII string)
  • UnixTimestampSeconds (long)
  • ReadingValue (decimal)
  • StatusCode (int)

We define the immutable domain model and batch container:
public readonly record struct TelemetryReading(
    string DeviceCode,
    long UnixTimestampSeconds,
    decimal ReadingValue,
    int StatusCode
);

public sealed class TelemetryBatch
{
    public List<TelemetryReading> Readings { get; } = [];
}

3. Implementing the Zero-Allocation Custom InputFormatter
When reading from PipeReader, a single line or field can occasionally straddle two ReadOnlyMemory<byte> segments inside a ReadOnlySequence<byte>. A production-grade formatter handles contiguous single-segment buffers on a fast path using ReadOnlySpan<byte> and Utf8Parser, while falling back to SequenceReader<byte> when a line spans multiple segments.
using System.Buffers;
using System.Buffers.Text;
using System.IO.Pipelines;
using System.Text;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.Net.Http.Headers;

public sealed class TelemetryBatchInputFormatter : InputFormatter
{
    private const byte PipeByte = (byte)'|';
    private const byte NewLineByte = (byte)'\n';
    private const byte CarriageReturnByte = (byte)'\r';
    private const int MaxBatchReadings = 10_000;

    public TelemetryBatchInputFormatter()
    {
        SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("text/x-telemetry-batch"));
    }

    protected override bool CanReadType(Type type)
    {
        return type == typeof(TelemetryBatch);
    }

    public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context)
    {
        ArgumentNullException.ThrowIfNull(context);

        var httpContext = context.HttpContext;
        var reader = httpContext.Request.BodyReader;
        var batch = new TelemetryBatch();
        int lineNumber = 0;

        try
        {
            while (true)
            {
                ReadResult result = await reader.ReadAsync(httpContext.RequestAborted);
                ReadOnlySequence<byte> buffer = result.Buffer;

                while (TryReadLine(ref buffer, out ReadOnlySequence<byte> lineSequence))
                {
                    lineNumber++;

                    if (batch.Readings.Count >= MaxBatchReadings)
                    {
                        context.ModelState.TryAddModelError(
                            context.ModelName,
                            $"Batch exceeds maximum allowed size of {MaxBatchReadings} readings.");
                        reader.AdvanceTo(buffer.End);
                        return await InputFormatterResult.FailureAsync();
                    }

                    if (!TryParseLine(lineSequence, out TelemetryReading reading, out string? error))
                    {
                        context.ModelState.TryAddModelError(
                            context.ModelName,
                            $"Line {lineNumber}: {error ?? "Invalid telemetry record format."}");
                        reader.AdvanceTo(buffer.End);
                        return await InputFormatterResult.FailureAsync();
                    }

                    batch.Readings.Add(reading);
                }

                // Tell the PipeReader how much of the buffer was consumed and examined
                reader.AdvanceTo(buffer.Start, buffer.End);

                if (result.IsCompleted)
                {
                    // Handle trailing data if the final line did not end with '\n'
                    if (!buffer.IsEmpty)
                    {
                        lineNumber++;
                        if (!TryParseLine(buffer, out TelemetryReading trailingReading, out string? error))
                        {
                            context.ModelState.TryAddModelError(
                                context.ModelName,
                                $"Line {lineNumber}: {error ?? "Invalid trailing telemetry record."}");
                            return await InputFormatterResult.FailureAsync();
                        }

                        batch.Readings.Add(trailingReading);
                        reader.AdvanceTo(buffer.End);
                    }

                    break;
                }
            }

            return await InputFormatterResult.SuccessAsync(batch);
        }
        catch (OperationCanceledException)
        {
            throw;
        }
        catch (Exception ex)
        {
            context.ModelState.TryAddModelError(
                context.ModelName,
                $"Error reading telemetry stream: {ex.Message}");
            return await InputFormatterResult.FailureAsync();
        }
    }

    private static bool TryReadLine(ref ReadOnlySequence<byte> buffer, out ReadOnlySequence<byte> line)
    {
        SequencePosition? position = buffer.PositionOf(NewLineByte);
        if (position is null)
        {
            line = default;
            return false;
        }

        line = buffer.Slice(0, position.Value);
        buffer = buffer.Slice(buffer.GetPosition(1, position.Value));
        return true;
    }

    private static bool TryParseLine(
        ReadOnlySequence<byte> line,
        out TelemetryReading reading,
        out string? error)
    {
        reading = default;
        error = null;

        // Fast path: entire line fits inside a single contiguous memory span
        if (line.IsSingleSegment)
        {
            return TryParseSpan(line.FirstSpan, out reading, out error);
        }

        // Fallback path for lines split across PipeReader segments
        var seqReader = new SequenceReader<byte>(line);
        if (!seqReader.TryReadTo(out ReadOnlySequence<byte> deviceSeq, PipeByte, advancePastDelimiter: true) ||
            !seqReader.TryReadTo(out ReadOnlySequence<byte> timestampSeq, PipeByte, advancePastDelimiter: true) ||
            !seqReader.TryReadTo(out ReadOnlySequence<byte> valueSeq, PipeByte, advancePastDelimiter: true))
        {
            error = "Expected 4 pipe-delimited fields.";
            return false;
        }

        ReadOnlySequence<byte> statusSeq = line.Slice(seqReader.Position);
        if (statusSeq.IsEmpty)
        {
            error = "Missing status code field.";
            return false;
        }

        string deviceCode = Encoding.ASCII.GetString(deviceSeq);
        if (string.IsNullOrWhiteSpace(deviceCode))
        {
            error = "Device code cannot be empty.";
            return false;
        }

        if (!TryParseInt64(timestampSeq, out long timestamp) ||
            !TryParseDecimal(valueSeq, out decimal value) ||
            !TryParseInt32(statusSeq, out int statusCode))
        {
            error = "One or more numeric fields could not be parsed.";
            return false;
        }

        reading = new TelemetryReading(deviceCode, timestamp, value, statusCode);
        return true;
    }

    private static bool TryParseSpan(
        ReadOnlySpan<byte> span,
        out TelemetryReading reading,
        out string? error)
    {
        reading = default;
        error = null;

        // Trim optional trailing '\r' from CRLF payloads
        if (!span.IsEmpty && span[^1] == CarriageReturnByte)
        {
            span = span[..^1];
        }

        if (span.IsEmpty)
        {
            error = "Empty telemetry line.";
            return false;
        }

        int idx1 = span.IndexOf(PipeByte);
        if (idx1 <= 0)
        {
            error = "Missing or invalid device code.";
            return false;
        }

        ReadOnlySpan<byte> deviceSpan = span[..idx1];
        ReadOnlySpan<byte> rest1 = span[(idx1 + 1)..];

        int idx2 = rest1.IndexOf(PipeByte);
        if (idx2 <= 0)
        {
            error = "Missing or invalid timestamp field.";
            return false;
        }

        ReadOnlySpan<byte> timestampSpan = rest1[..idx2];
        ReadOnlySpan<byte> rest2 = rest1[(idx2 + 1)..];

        int idx3 = rest2.IndexOf(PipeByte);
        if (idx3 <= 0)
        {
            error = "Missing or invalid reading value field.";
            return false;
        }

        ReadOnlySpan<byte> valueSpan = rest2[..idx3];
        ReadOnlySpan<byte> statusSpan = rest2[(idx3 + 1)..];

        if (statusSpan.IsEmpty)
        {
            error = "Missing status code field.";
            return false;
        }

        if (!Utf8Parser.TryParse(timestampSpan, out long timestamp, out int tsConsumed, 'D') ||
            tsConsumed != timestampSpan.Length)
        {
            error = "Invalid integer timestamp.";
            return false;
        }

        if (!Utf8Parser.TryParse(valueSpan, out decimal value, out int valConsumed) ||
            valConsumed != valueSpan.Length)
        {
            error = "Invalid decimal reading value.";
            return false;
        }

        if (!Utf8Parser.TryParse(statusSpan, out int statusCode, out int statusConsumed, 'D') ||
            statusConsumed != statusSpan.Length)
        {
            error = "Invalid integer status code.";
            return false;
        }

        string deviceCode = Encoding.ASCII.GetString(deviceSpan);
        reading = new TelemetryReading(deviceCode, timestamp, value, statusCode);
        return true;
    }

    private static bool TryParseInt64(ReadOnlySequence<byte> seq, out long value)
    {
        if (seq.IsSingleSegment)
        {
            return Utf8Parser.TryParse(seq.FirstSpan, out value, out int consumed, 'D') &&
                   consumed == seq.FirstSpan.Length;
        }

        Span<byte> stackBuf = stackalloc byte[32];
        if (seq.Length > stackBuf.Length)
        {
            value = 0;
            return false;
        }

        seq.CopyTo(stackBuf);
        return Utf8Parser.TryParse(stackBuf[..(int)seq.Length], out value, out int consumed, 'D') &&
               consumed == seq.Length;
    }

    private static bool TryParseDecimal(ReadOnlySequence<byte> seq, out decimal value)
    {
        if (seq.IsSingleSegment)
        {
            return Utf8Parser.TryParse(seq.FirstSpan, out value, out int consumed) &&
                   consumed == seq.FirstSpan.Length;
        }

        Span<byte> stackBuf = stackalloc byte[64];
        if (seq.Length > stackBuf.Length)
        {
            value = 0;
            return false;
        }

        seq.CopyTo(stackBuf);
        return Utf8Parser.TryParse(stackBuf[..(int)seq.Length], out value, out int consumed) &&
               consumed == seq.Length;
    }

    private static bool TryParseInt32(ReadOnlySequence<byte> seq, out int value)
    {
        if (seq.IsSingleSegment)
        {
            return Utf8Parser.TryParse(seq.FirstSpan, out value, out int consumed, 'D') &&
                   consumed == seq.FirstSpan.Length;
        }

        Span<byte> stackBuf = stackalloc byte[16];
        if (seq.Length > stackBuf.Length)
        {
            value = 0;
            return false;
        }

        seq.CopyTo(stackBuf);
        return Utf8Parser.TryParse(stackBuf[..(int)seq.Length], out value, out int consumed, 'D') &&
               consumed == seq.Length;
    }
}


4. Registering the Formatter & Consuming It in an MVC Controller
Programmatic Registration (Program.cs)

Insert TelemetryBatchInputFormatter into MvcOptions.InputFormatters so MVC invokes it automatically when a request carries Content-Type: text/x-telemetry-batch and targets TelemetryBatch.
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers(options =>
{
    options.InputFormatters.Insert(0, new TelemetryBatchInputFormatter());
});

var app = builder.Build();
app.MapControllers();
app.Run();


Controller Action (TelemetryController.cs)
The controller action receives a validated TelemetryBatch without ever touching raw streams, StreamReader, or string splitting logic:

using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/telemetry")]
public sealed class TelemetryController : ControllerBase
{
    private readonly ILogger<TelemetryController> _logger;

    public TelemetryController(ILogger<TelemetryController> logger)
    {
        _logger = logger;
    }

    [HttpPost("ingest")]
    [Consumes("text/x-telemetry-batch")]
    public IActionResult Ingest([FromBody] TelemetryBatch batch)
    {
        if (!ModelState.IsValid)
        {
            return ValidationProblem(ModelState);
        }

        decimal totalReading = 0m;
        foreach (var reading in batch.Readings)
        {
            totalReading += reading.ReadingValue;
        }

        _logger.LogInformation(
            "Ingested {Count} telemetry readings with total value {Total}.",
            batch.Readings.Count,
            totalReading);

        return Ok(new
        {
            AcceptedCount = batch.Readings.Count,
            TotalReadingValue = totalReading
        });
    }
}

5. Verifying Behavior and Allocation Profile
You can verify both correctness and allocation behavior using integration tests with WebApplicationFactory<Program> and microbenchmarks with BenchmarkDotNet:
using System.Net;
using System.Net.Http.Headers;
using System.Text;
using Microsoft.AspNetCore.Mvc.Testing;
using Xunit;

public sealed class TelemetryControllerTests : IClassFixture<WebApplicationFactory<Program>>
{
    private readonly WebApplicationFactory<Program> _factory;

    public TelemetryControllerTests(WebApplicationFactory<Program> factory)
    {
        _factory = factory;
    }

    [Fact]
    public async Task Ingest_ValidPipeDelimitedBatch_ReturnsAcceptedSummary()
    {
        using var client = _factory.CreateClient();
        const string payload = "MTR-01|1732000800|125.50|200\nMTR-02|1732000805|74.50|200\n";

        using var content = new StringContent(payload, Encoding.ASCII);
        content.Headers.ContentType = new MediaTypeHeaderValue("text/x-telemetry-batch");

        var response = await client.PostAsync("/api/telemetry/ingest", content);

        Assert.Equal(HttpStatusCode.OK, response.StatusCode);
    }

    [Fact]
    public async Task Ingest_MalformedNumericField_ReturnsValidationProblem()
    {
        using var client = _factory.CreateClient();
        const string payload = "MTR-01|NOT_A_TIMESTAMP|125.50|200\n";

        using var content = new StringContent(payload, Encoding.ASCII);
        content.Headers.ContentType = new MediaTypeHeaderValue("text/x-telemetry-batch");

        var response = await client.PostAsync("/api/telemetry/ingest", content);

        Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
    }
}

When benchmarking TelemetryBatchInputFormatter with BenchmarkDotNet ([MemoryDiagnoser]), keep two practical rules in mind:
Test both single-segment and multi-segment ReadOnlySequence<byte> inputs: A real network pipe often splits payloads across segments, so verify that your SequenceReader<byte> fallback produces identical results to the contiguous ReadOnlySpan<byte> fast path.

Guard against untrusted input sizes: Always enforce explicit line/batch limits (MaxBatchReadings) and validate Utf8Parser consumed byte counts (consumed == span.Length) so trailing garbage characters cannot slip past partial parses.

Conclusion
Pairing PipeReader, ReadOnlySpan<byte> / Utf8Parser, and a custom InputFormatter gives ASP.NET Core MVC applications a clean, high-throughput path for ingesting custom or high-volume payloads. Instead of buffering full request bodies into strings and allocating intermediate arrays per line, your application streams bytes directly from the network pipeline, validates malformed records early via ModelState, and hands clean domain models to your controllers with drastically lower GC pressure and tighter tail latency.



ASP.NET MVC Hosting - HostForLIFE.eu :: End-to-End Masterclass: Using Span<T>, PipeReader, and Custom InputFormatter in ASP.NET Core MVC to Optimise Zero-Allocation Performance

clock November 20, 2026 12:33 by author Peter

When ASP.NET Core MVC endpoints process high-frequency webhooks, telemetry batches, or custom delimited payloads, default deserialisation pipelines can become a major source of memory churn. Reading an entire request stream into a string or byte[] array, splitting substrings with string.Split, and parsing individual tokens with int.Parse(string) or decimal.Parse(string) allocating heap objects on every request. Under heavy load, those short-lived allocations pressure the Garbage Collector (GC), trigger Gen0/Gen1/Gen2 collections, and spike tail (p99) latency.

By combining System.IO.Pipelines (PipeReader), ReadOnlySpan<byte> / ReadOnlySequence<byte>, and a custom TextInputFormatter / InputFormatter, you can stream incoming request bytes directly from Kestrel and parse structured records with minimal or zero heap allocations per record. This guide walks through how to design, implement, register, and benchmark a zero-allocation custom input formatter in ASP.NET Core MVC.

1. Architectural Blueprint & Allocation Hotspots
Understanding where allocations happen in standard request ingestion helps explain why PipeReader and Span<T> are so effective:

Stage

Naive Stream/String Approach

Zero-Allocation PipeReader + Span<byte> Approach

Stream Reading

StreamReader.ReadToEndAsync() buffers the entire body into a large string on the heap.

HttpContext.Request.BodyReader (PipeReader) yields ReadOnlySequence<byte> chunks as network buffers arrive.

Tokenization

`line.Split('

')allocates astring[]plus astring` instance for every field.

Type Parsing

decimal.Parse(fieldStr) requires a string and culture-heavy overhead.

Utf8Parser.TryParse(fieldSpan, out decimal value, out _) parses ASCII/UTF-8 digits straight from bytes.

HTTP Request Body (Kestrel Socket / Pipe)
   │
   ▼
[PipeReader (HttpContext.Request.BodyReader)]
   │  Reads ReadOnlySequence<byte> segments without copying entire payload
   ▼
[Custom InputFormatter (TelemetryBatchInputFormatter)]
   │  Handles single-segment Span<byte> fast path + multi-segment SequenceReader fallback
   │  Parses fields with Utf8Parser.TryParse (zero string allocations)
   ▼
[Strongly Typed Domain Model (TelemetryBatch)]
   │
   ▼
[MVC Controller Action]


2. Target Domain Model & Wire Format
Suppose an ingestion endpoint receives high-throughput metering or telemetry batches formatted as newline-delimited pipe records (|-separated):

METER-1001|1732000800|148.75|200
METER-1002|1732000801|312.40|200


Each line contains:

  • DeviceCode (ASCII string)
  • UnixTimestampSeconds (long)
  • ReadingValue (decimal)
  • StatusCode (int)

We define the immutable domain model and batch container:
public readonly record struct TelemetryReading(
    string DeviceCode,
    long UnixTimestampSeconds,
    decimal ReadingValue,
    int StatusCode
);

public sealed class TelemetryBatch
{
    public List<TelemetryReading> Readings { get; } = [];
}

3. Implementing the Zero-Allocation Custom InputFormatter
When reading from PipeReader, a single line or field can occasionally straddle two ReadOnlyMemory<byte> segments inside a ReadOnlySequence<byte>. A production-grade formatter handles contiguous single-segment buffers on a fast path using ReadOnlySpan<byte> and Utf8Parser, while falling back to SequenceReader<byte> when a line spans multiple segments.
using System.Buffers;
using System.Buffers.Text;
using System.IO.Pipelines;
using System.Text;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.Net.Http.Headers;

public sealed class TelemetryBatchInputFormatter : InputFormatter
{
    private const byte PipeByte = (byte)'|';
    private const byte NewLineByte = (byte)'\n';
    private const byte CarriageReturnByte = (byte)'\r';
    private const int MaxBatchReadings = 10_000;

    public TelemetryBatchInputFormatter()
    {
        SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("text/x-telemetry-batch"));
    }

    protected override bool CanReadType(Type type)
    {
        return type == typeof(TelemetryBatch);
    }

    public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context)
    {
        ArgumentNullException.ThrowIfNull(context);

        var httpContext = context.HttpContext;
        var reader = httpContext.Request.BodyReader;
        var batch = new TelemetryBatch();
        int lineNumber = 0;

        try
        {
            while (true)
            {
                ReadResult result = await reader.ReadAsync(httpContext.RequestAborted);
                ReadOnlySequence<byte> buffer = result.Buffer;

                while (TryReadLine(ref buffer, out ReadOnlySequence<byte> lineSequence))
                {
                    lineNumber++;

                    if (batch.Readings.Count >= MaxBatchReadings)
                    {
                        context.ModelState.TryAddModelError(
                            context.ModelName,
                            $"Batch exceeds maximum allowed size of {MaxBatchReadings} readings.");
                        reader.AdvanceTo(buffer.End);
                        return await InputFormatterResult.FailureAsync();
                    }

                    if (!TryParseLine(lineSequence, out TelemetryReading reading, out string? error))
                    {
                        context.ModelState.TryAddModelError(
                            context.ModelName,
                            $"Line {lineNumber}: {error ?? "Invalid telemetry record format."}");
                        reader.AdvanceTo(buffer.End);
                        return await InputFormatterResult.FailureAsync();
                    }

                    batch.Readings.Add(reading);
                }

                // Tell the PipeReader how much of the buffer was consumed and examined
                reader.AdvanceTo(buffer.Start, buffer.End);

                if (result.IsCompleted)
                {
                    // Handle trailing data if the final line did not end with '\n'
                    if (!buffer.IsEmpty)
                    {
                        lineNumber++;
                        if (!TryParseLine(buffer, out TelemetryReading trailingReading, out string? error))
                        {
                            context.ModelState.TryAddModelError(
                                context.ModelName,
                                $"Line {lineNumber}: {error ?? "Invalid trailing telemetry record."}");
                            return await InputFormatterResult.FailureAsync();
                        }

                        batch.Readings.Add(trailingReading);
                        reader.AdvanceTo(buffer.End);
                    }

                    break;
                }
            }

            return await InputFormatterResult.SuccessAsync(batch);
        }
        catch (OperationCanceledException)
        {
            throw;
        }
        catch (Exception ex)
        {
            context.ModelState.TryAddModelError(
                context.ModelName,
                $"Error reading telemetry stream: {ex.Message}");
            return await InputFormatterResult.FailureAsync();
        }
    }

    private static bool TryReadLine(ref ReadOnlySequence<byte> buffer, out ReadOnlySequence<byte> line)
    {
        SequencePosition? position = buffer.PositionOf(NewLineByte);
        if (position is null)
        {
            line = default;
            return false;
        }

        line = buffer.Slice(0, position.Value);
        buffer = buffer.Slice(buffer.GetPosition(1, position.Value));
        return true;
    }

    private static bool TryParseLine(
        ReadOnlySequence<byte> line,
        out TelemetryReading reading,
        out string? error)
    {
        reading = default;
        error = null;

        // Fast path: entire line fits inside a single contiguous memory span
        if (line.IsSingleSegment)
        {
            return TryParseSpan(line.FirstSpan, out reading, out error);
        }

        // Fallback path for lines split across PipeReader segments
        var seqReader = new SequenceReader<byte>(line);
        if (!seqReader.TryReadTo(out ReadOnlySequence<byte> deviceSeq, PipeByte, advancePastDelimiter: true) ||
            !seqReader.TryReadTo(out ReadOnlySequence<byte> timestampSeq, PipeByte, advancePastDelimiter: true) ||
            !seqReader.TryReadTo(out ReadOnlySequence<byte> valueSeq, PipeByte, advancePastDelimiter: true))
        {
            error = "Expected 4 pipe-delimited fields.";
            return false;
        }

        ReadOnlySequence<byte> statusSeq = line.Slice(seqReader.Position);
        if (statusSeq.IsEmpty)
        {
            error = "Missing status code field.";
            return false;
        }

        string deviceCode = Encoding.ASCII.GetString(deviceSeq);
        if (string.IsNullOrWhiteSpace(deviceCode))
        {
            error = "Device code cannot be empty.";
            return false;
        }

        if (!TryParseInt64(timestampSeq, out long timestamp) ||
            !TryParseDecimal(valueSeq, out decimal value) ||
            !TryParseInt32(statusSeq, out int statusCode))
        {
            error = "One or more numeric fields could not be parsed.";
            return false;
        }

        reading = new TelemetryReading(deviceCode, timestamp, value, statusCode);
        return true;
    }

    private static bool TryParseSpan(
        ReadOnlySpan<byte> span,
        out TelemetryReading reading,
        out string? error)
    {
        reading = default;
        error = null;

        // Trim optional trailing '\r' from CRLF payloads
        if (!span.IsEmpty && span[^1] == CarriageReturnByte)
        {
            span = span[..^1];
        }

        if (span.IsEmpty)
        {
            error = "Empty telemetry line.";
            return false;
        }

        int idx1 = span.IndexOf(PipeByte);
        if (idx1 <= 0)
        {
            error = "Missing or invalid device code.";
            return false;
        }

        ReadOnlySpan<byte> deviceSpan = span[..idx1];
        ReadOnlySpan<byte> rest1 = span[(idx1 + 1)..];

        int idx2 = rest1.IndexOf(PipeByte);
        if (idx2 <= 0)
        {
            error = "Missing or invalid timestamp field.";
            return false;
        }

        ReadOnlySpan<byte> timestampSpan = rest1[..idx2];
        ReadOnlySpan<byte> rest2 = rest1[(idx2 + 1)..];

        int idx3 = rest2.IndexOf(PipeByte);
        if (idx3 <= 0)
        {
            error = "Missing or invalid reading value field.";
            return false;
        }

        ReadOnlySpan<byte> valueSpan = rest2[..idx3];
        ReadOnlySpan<byte> statusSpan = rest2[(idx3 + 1)..];

        if (statusSpan.IsEmpty)
        {
            error = "Missing status code field.";
            return false;
        }

        if (!Utf8Parser.TryParse(timestampSpan, out long timestamp, out int tsConsumed, 'D') ||
            tsConsumed != timestampSpan.Length)
        {
            error = "Invalid integer timestamp.";
            return false;
        }

        if (!Utf8Parser.TryParse(valueSpan, out decimal value, out int valConsumed) ||
            valConsumed != valueSpan.Length)
        {
            error = "Invalid decimal reading value.";
            return false;
        }

        if (!Utf8Parser.TryParse(statusSpan, out int statusCode, out int statusConsumed, 'D') ||
            statusConsumed != statusSpan.Length)
        {
            error = "Invalid integer status code.";
            return false;
        }

        string deviceCode = Encoding.ASCII.GetString(deviceSpan);
        reading = new TelemetryReading(deviceCode, timestamp, value, statusCode);
        return true;
    }

    private static bool TryParseInt64(ReadOnlySequence<byte> seq, out long value)
    {
        if (seq.IsSingleSegment)
        {
            return Utf8Parser.TryParse(seq.FirstSpan, out value, out int consumed, 'D') &&
                   consumed == seq.FirstSpan.Length;
        }

        Span<byte> stackBuf = stackalloc byte[32];
        if (seq.Length > stackBuf.Length)
        {
            value = 0;
            return false;
        }

        seq.CopyTo(stackBuf);
        return Utf8Parser.TryParse(stackBuf[..(int)seq.Length], out value, out int consumed, 'D') &&
               consumed == seq.Length;
    }

    private static bool TryParseDecimal(ReadOnlySequence<byte> seq, out decimal value)
    {
        if (seq.IsSingleSegment)
        {
            return Utf8Parser.TryParse(seq.FirstSpan, out value, out int consumed) &&
                   consumed == seq.FirstSpan.Length;
        }

        Span<byte> stackBuf = stackalloc byte[64];
        if (seq.Length > stackBuf.Length)
        {
            value = 0;
            return false;
        }

        seq.CopyTo(stackBuf);
        return Utf8Parser.TryParse(stackBuf[..(int)seq.Length], out value, out int consumed) &&
               consumed == seq.Length;
    }

    private static bool TryParseInt32(ReadOnlySequence<byte> seq, out int value)
    {
        if (seq.IsSingleSegment)
        {
            return Utf8Parser.TryParse(seq.FirstSpan, out value, out int consumed, 'D') &&
                   consumed == seq.FirstSpan.Length;
        }

        Span<byte> stackBuf = stackalloc byte[16];
        if (seq.Length > stackBuf.Length)
        {
            value = 0;
            return false;
        }

        seq.CopyTo(stackBuf);
        return Utf8Parser.TryParse(stackBuf[..(int)seq.Length], out value, out int consumed, 'D') &&
               consumed == seq.Length;
    }
}


4. Registering the Formatter & Consuming It in an MVC Controller
Programmatic Registration (Program.cs)

Insert TelemetryBatchInputFormatter into MvcOptions.InputFormatters so MVC invokes it automatically when a request carries Content-Type: text/x-telemetry-batch and targets TelemetryBatch.
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers(options =>
{
    options.InputFormatters.Insert(0, new TelemetryBatchInputFormatter());
});

var app = builder.Build();
app.MapControllers();
app.Run();


Controller Action (TelemetryController.cs)
The controller action receives a validated TelemetryBatch without ever touching raw streams, StreamReader, or string splitting logic:

using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/telemetry")]
public sealed class TelemetryController : ControllerBase
{
    private readonly ILogger<TelemetryController> _logger;

    public TelemetryController(ILogger<TelemetryController> logger)
    {
        _logger = logger;
    }

    [HttpPost("ingest")]
    [Consumes("text/x-telemetry-batch")]
    public IActionResult Ingest([FromBody] TelemetryBatch batch)
    {
        if (!ModelState.IsValid)
        {
            return ValidationProblem(ModelState);
        }

        decimal totalReading = 0m;
        foreach (var reading in batch.Readings)
        {
            totalReading += reading.ReadingValue;
        }

        _logger.LogInformation(
            "Ingested {Count} telemetry readings with total value {Total}.",
            batch.Readings.Count,
            totalReading);

        return Ok(new
        {
            AcceptedCount = batch.Readings.Count,
            TotalReadingValue = totalReading
        });
    }
}

5. Verifying Behavior and Allocation Profile
You can verify both correctness and allocation behavior using integration tests with WebApplicationFactory<Program> and microbenchmarks with BenchmarkDotNet:
using System.Net;
using System.Net.Http.Headers;
using System.Text;
using Microsoft.AspNetCore.Mvc.Testing;
using Xunit;

public sealed class TelemetryControllerTests : IClassFixture<WebApplicationFactory<Program>>
{
    private readonly WebApplicationFactory<Program> _factory;

    public TelemetryControllerTests(WebApplicationFactory<Program> factory)
    {
        _factory = factory;
    }

    [Fact]
    public async Task Ingest_ValidPipeDelimitedBatch_ReturnsAcceptedSummary()
    {
        using var client = _factory.CreateClient();
        const string payload = "MTR-01|1732000800|125.50|200\nMTR-02|1732000805|74.50|200\n";

        using var content = new StringContent(payload, Encoding.ASCII);
        content.Headers.ContentType = new MediaTypeHeaderValue("text/x-telemetry-batch");

        var response = await client.PostAsync("/api/telemetry/ingest", content);

        Assert.Equal(HttpStatusCode.OK, response.StatusCode);
    }

    [Fact]
    public async Task Ingest_MalformedNumericField_ReturnsValidationProblem()
    {
        using var client = _factory.CreateClient();
        const string payload = "MTR-01|NOT_A_TIMESTAMP|125.50|200\n";

        using var content = new StringContent(payload, Encoding.ASCII);
        content.Headers.ContentType = new MediaTypeHeaderValue("text/x-telemetry-batch");

        var response = await client.PostAsync("/api/telemetry/ingest", content);

        Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
    }
}

When benchmarking TelemetryBatchInputFormatter with BenchmarkDotNet ([MemoryDiagnoser]), keep two practical rules in mind:
Test both single-segment and multi-segment ReadOnlySequence<byte> inputs: A real network pipe often splits payloads across segments, so verify that your SequenceReader<byte> fallback produces identical results to the contiguous ReadOnlySpan<byte> fast path.

Guard against untrusted input sizes: Always enforce explicit line/batch limits (MaxBatchReadings) and validate Utf8Parser consumed byte counts (consumed == span.Length) so trailing garbage characters cannot slip past partial parses.

Conclusion
Pairing PipeReader, ReadOnlySpan<byte> / Utf8Parser, and a custom InputFormatter gives ASP.NET Core MVC applications a clean, high-throughput path for ingesting custom or high-volume payloads. Instead of buffering full request bodies into strings and allocating intermediate arrays per line, your application streams bytes directly from the network pipeline, validates malformed records early via ModelState, and hands clean domain models to your controllers with drastically lower GC pressure and tighter tail latency.



ASP.NET MVC Hosting - HostForLIFE.eu :: Using jQuery and ADO.NET, Basic AJAX CRUD in ASP.NET MVC

clock November 17, 2026 16:48 by author Peter

A quick and seamless user experience is essential for modern online apps. The program becomes sluggish and less engaging if a page reloads each time we add or modify data. This is where asynchronous JavaScript and XML, or AJAX, comes in handy. We can interact with the server using AJAX without having to completely reload the page.

We will construct a basic student CRUD application in this post using:

In this article, we will build a simple Student CRUD application using:

  • ASP.NET MVC
  • jQuery AJAX
  • ADO.NET
  • SQL Server

This example is designed for beginners, so every step is explained in simple words.

What is CRUD?
CRUD is a common term used in database applications.

OperationMeaning
Create Insert new data
Read Display data
Update Modify existing data
Delete Remove data

Most web applications use CRUD operations.

Technologies Used

In this example we will use:

  • ASP.NET MVC
  • jQuery
  • AJAX
  • SQL Server
  • ADO.NET

This approach helps beginners understand how database communication works without using ORM frameworks.

Step 1 – Create Database Table
First, create a table in SQL Server.
CREATE TABLE Students
(
    Id INT PRIMARY KEY IDENTITY(1,1),
    Name NVARCHAR(100),
    Age INT
)


This table will store student information.

Step 2 – Create MVC Project
Open Visual Studio
Create a new project:
ASP.NET Web Application → MVC
After creating the project, add a Model class.

Step 3 – Create Model Class
Create a class named Student.cs inside the Models folder.
public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}


This class represents the Students table structure.

Step 4 – Add Database Connection

Open Web.config and add a connection string.
<connectionStrings>
  <add name="dbcon"
       connectionString="Data Source=.;Initial Catalog=StudentDB;Integrated Security=True"
       providerName="System.Data.SqlClient" />
</connectionStrings>


This connection allows the application to communicate with SQL Server.

Step 5 – Create Controller

Now create StudentController.
Import required namespaces:

using System.Data.SqlClient;
using System.Configuration;
using System.Data;

Index Method

public ActionResult Index()
{
    return View();
}


This method simply returns the main page.

Step 6 – Read Data from Database

public JsonResult GetStudents()
{
    List<Student> list = new List<Student>();

    string cs = ConfigurationManager.ConnectionStrings["dbcon"].ConnectionString;

    using (SqlConnection con = new SqlConnection(cs))
    {
        SqlCommand cmd = new SqlCommand("SELECT * FROM Students", con);
        con.Open();
        SqlDataReader dr = cmd.ExecuteReader();

        while (dr.Read())
        {
            list.Add(new Student
            {
                Id = Convert.ToInt32(dr["Id"]),
                Name = dr["Name"].ToString(),
                Age = Convert.ToInt32(dr["Age"])
            });
        }
    }

    return Json(list, JsonRequestBehavior.AllowGet);
}

This method retrieves all students from the database.

Step 7 – Insert Data

[HttpPost]
public JsonResult Insert(Student s)
{
    string cs = ConfigurationManager.ConnectionStrings["dbcon"].ConnectionString;

    using (SqlConnection con = new SqlConnection(cs))
    {
        string query = "INSERT INTO Students(Name,Age) VALUES(@Name,@Age)";
        SqlCommand cmd = new SqlCommand(query, con);

        cmd.Parameters.AddWithValue("@Name", s.Name);
        cmd.Parameters.AddWithValue("@Age", s.Age);

        con.Open();
        cmd.ExecuteNonQuery();
    }

    return Json(true);
}

This method inserts new student data into the database.

Step 8 – Update Data

[HttpPost]
public JsonResult Update(Student s)
{
    string cs = ConfigurationManager.ConnectionStrings["dbcon"].ConnectionString;

    using (SqlConnection con = new SqlConnection(cs))
    {
        string query = "UPDATE Students SET Name=@Name, Age=@Age WHERE Id=@Id";

        SqlCommand cmd = new SqlCommand(query, con);
        cmd.Parameters.AddWithValue("@Id", s.Id);
        cmd.Parameters.AddWithValue("@Name", s.Name);
        cmd.Parameters.AddWithValue("@Age", s.Age);

        con.Open();
        cmd.ExecuteNonQuery();
    }

    return Json(true);
}

This method updates existing student records.

Step 9 – Delete Data

[HttpPost]
public JsonResult Delete(int id)
{
    string cs = ConfigurationManager.ConnectionStrings["dbcon"].ConnectionString;

    using (SqlConnection con = new SqlConnection(cs))
    {
        SqlCommand cmd = new SqlCommand("DELETE FROM Students WHERE Id=@Id", con);
        cmd.Parameters.AddWithValue("@Id", id);

        con.Open();
        cmd.ExecuteNonQuery();
    }

    return Json(true);
}

This method deletes a student record.

Step 10 – Create View

Inside Index.cshtml
<h2>Student Management</h2>

<input type="hidden" id="Id" />

Name
<input type="text" id="Name" />

Age
<input type="number" id="Age" />

<button onclick="Save()">Save</button>

<hr>

<table border="1">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Action</th>
</tr>
</thead>

<tbody id="studentTable"></tbody>
</table>


Step 11 – Add jQuery
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

Step 12 – AJAX Code

$(document).ready(function () {
    loadStudents();
});

function loadStudents() {
    $.get("/Student/GetStudents", function (data) {

        var rows = "";

        $.each(data, function (i, item) {

            rows += "<tr>";
            rows += "<td>" + item.Name + "</td>";
            rows += "<td>" + item.Age + "</td>";
            rows += "<td>";

            rows += "<button onclick='editStudent(" + item.Id + ",\"" + item.Name + "\"," + item.Age + ")'>Edit</button>";

            rows += "<button onclick='deleteStudent(" + item.Id + ")'>Delete</button>";

            rows += "</td>";
            rows += "</tr>";
        });

        $("#studentTable").html(rows);
    });
}

Application Output
The application allows users to:

  • Add new students
  • View students instantly
  • Edit existing records
  • Delete records

All operations work without refreshing the page, making the application faster and smoother.

Why Use AJAX in MVC?
AJAX improves web applications by:

  • Reducing page reloads
  • Making applications faster
  • Providing better user experience
  • Loading data dynamically

Because of these benefits, AJAX is widely used in modern web applications.

Conclusion
In this article, we built a simple CRUD application using ASP.NET MVC, jQuery AJAX, and ADO.NET.

We learned:

  • How to connect MVC with SQL Server
  • How to perform CRUD operations
  • How AJAX helps update data without refreshing the page


ASP.NET MVC Hosting - HostForLIFE.eu :: Running ASP.NET WebForms, MVC and Web API on .NET 10 with Kestrel

clock November 11, 2026 13:35 by author Peter

You've heard the same advice for years if you manage a traditional ASP.NET site that includes WebForms pages, MVC controllers,.asmx web services, and perhaps a few.svc WCF endpoints: rework it. system.The official migration story is a slow rewriting behind a YARP proxy, Web never made the switch to.NET Core, and Microsoft has stated that it never will.

This article presents a different option: a port of the ASP.NET stack itself—WebForms, MVC 4, Razor, Web Pages, Web API, .asmx, and .svc hosting—to .NET 10, running under Kestrel instead of IIS. Your .aspx, .ascx, .master, .cshtml, code-behind, controllers, and web.config stay exactly as they are. System.Web.UI.Page is still System.Web.UI.Page; System.Web.Mvc.Controller is still System.Web.Mvc.Controller. What changes is the host and the project file—not your application code.

The port is built from Mono's open-source implementation of System.Web and Microsoft's open-source aspnetwebstack (MVC, Razor, Web API), compiled in place against .NET 10, with the IIS/AppDomain-specific machinery replaced by an ASP.NET Core middleware.

The Problem: Why System.Web Never Came Along

Three hard blockers kept System.Web off .NET Core, and each needed a real answer.

1. The Assembly Identity Is Taken
Modern .NET ships an empty System.Web.dll facade inside the shared framework, and the runtime gives the shared framework precedence. An app-local System.Web.dll compiles fine and then fails at startup with FileNotFoundException.

The port therefore ships its assemblies under new names (Core.Web, Core.Configuration, and so on) while keeping the namespaces untouched, so your code and your generated page classes never notice.

2. Runtime Page Compilation Used CodeDOM

On .NET Core, CodeDomProvider's compile functionality throws PlatformNotSupportedException.

The port keeps CodeDOM for code generation (which still works) and hands the generated code to Roslyn for compilation.

Both C# and VB.NET pages compile at runtime, just as they did under IIS.

3. BinaryFormatter Is Gone
View state and out-of-process session state used BinaryFormatter for arbitrary object graphs.

Rather than silently replacing it with something insecure, the port refuses a type with no native encoding and reports which type caused the issue. You then opt in to a serializer (a JSON-based serializer is included, or you can provide your own).

Hosting: One Extension Method

The entire hosting model is a single ASP.NET Core extension method: UseWebForms.

Here is the complete Program.cs of a working WebForms application:
using Microsoft.AspNetCore.Builder;
using System.Web.Hosting.Kestrel;

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

// Static files first: let Kestrel serve .css/.js/images directly rather than
// routing them through the System.Web pipeline.
app.UseStaticFiles();

app.UseWebForms(options =>
{
    options.PhysicalPath = app.Environment.ContentRootPath;
    options.VirtualPath = "/";
    options.SiteName = "WebFormsSample";

    // Opt in to a serializer for state objects with no native encoding.
    options.StateSerializer = new System.Web.JsonStateObjectSerializer();
});

app.Run();


That is the entire host.

Behind UseWebForms, the port initializes the System.Web runtime (HttpRuntime, BuildManager, the module and handler pipeline, configuration) inside a single process. Since there are no AppDomains anymore, an adapter maps each incoming ASP.NET Core request onto an HttpWorkerRequest, exactly the abstraction IIS previously supplied.

Everything downstream remains the ASP.NET you already know:

  • web.config is read with full <location>, inheritance, and <httpModules> / <httpHandlers> semantics.
  • Global.asax, HttpApplication events, custom modules, and handlers run unchanged.
  • Postbacks, __VIEWSTATE, validators, master pages, user controls, GridView, Repeater, UpdatePanel, and ScriptManager all work.
  • App_Code is still compiled at runtime by BuildManager.

Your Pages Don't Change
To make the point concrete, here is code-behind from the sample application. There is nothing unusual to see—and that is the point.

This is ordinary WebForms code running on .NET 10.
public class DefaultPage : Page
{
    protected Label message;
    protected Label counter;
    protected Repeater items;
    protected GridView grid;

    // Survives postbacks through __VIEWSTATE, not a field.
    int PostbackCount
    {
        get
        {
            object v = ViewState["postbacks"];
            return v == null ? 0 : (int)v;
        }
        set
        {
            ViewState["postbacks"] = value;
        }
    }

    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);

        message.Text = IsPostBack
            ? "hello again (postback)"
            : "hello from Page_Load";

        if (IsPostBack)
            PostbackCount = PostbackCount + 1;

        counter.Text = PostbackCount.ToString();

        if (!IsPostBack)
        {
            items.DataSource = new List<string>
            {
                "alpha",
                "beta",
                "gamma"
            };

            items.DataBind();
        }
    }
}

MVC, Web API, and the Rest of the Stack
MVC is not a separate host. Under classic ASP.NET, it was always just an HttpModule and a handler registered inside System.Web, and the same is true here.

The MVC sample host is almost identical to the WebForms host.

app.UseWebForms(options =>
{
    options.PhysicalPath = app.Environment.ContentRootPath;
    options.VirtualPath = "/";
    options.SiteName = "MvcSample";

    // Controllers are discovered by scanning loaded assemblies.
    options.ApplicationAssemblies =
        new[]
        {
            typeof(MvcSample.Controllers.HomeController).Assembly
        };
});

Supported Framework Components

StackStatus on .NET 10

WebForms (.aspx, .ascx, .master)

Works, C# and VB.NET, runtime compiled by Roslyn

ASP.NET MVC

MVC 4 with Razor v2, attribute routing ([Route]), bundling, and @await in views

Web Pages (.cshtml)

Works

Web API

Works with routing, content negotiation, and model binding

.asmx SOAP services

Works

.svc WCF services

Served by CoreWCF at the same URLs; [ServiceContract] moves from System.ServiceModel to CoreWCF

Session State

InProc, StateServer (reimplemented over IDistributedCache), and SQLServer using ASPState database with unchanged web.config

Dynamic Data / LinqDataSource

Works using IQueryable and EF Core

Script and Style Bundling

System.Web.Optimization works

System.Web.Mail

Works unchanged

Getting Started
A single package reference is enough for a WebForms application. It transitively brings in the core of the port (AspNetCore.Web.Base, which contains the Core.Web assembly, along with configuration, services, and extensions). Its build assets also perform important project setup automatically.

Facade Removal
The empty .NET System.Web.dll and System.Configuration.dll facades are removed from the reference set.
Without this, you would encounter CS0433 type conflicts during compilation.
The build targets also verify that Core.Web.dll is copied to the output directory, turning what would otherwise be a runtime TypeLoadException into a clear build-time error.

Content Handling

The build process automatically copies:

  • .aspx
  • .cshtml
  • web.config

and related content beside your application assembly.

App_Code is copied as content because it is compiled by the runtime rather than MSBuild.

The bin and obj folders are excluded.

Afterward, simply add one package for each additional framework you use:

  • AspNetCore.Web.Mvc for MVC
  • AspNetCore.Web.Http
  • AspNetCore.Web.Http.WebHost
  • AspNetCore.Net.Http.Formatting for Web API
  • AspNetCore.Web.ServiceModel for .svc

AspNetCore.Web.SessionState for out-of-process session support
Notice the deliberate naming split:

  • Package: AspNetCore.Web.Base
  • Assembly: Core.Web
  • Namespace: System.Web

The assembly name is only exposed when explicitly referenced in web.config.

Honest Limitations

A port is only trustworthy if it clearly explains what it does not support.

  • .NET Remoting (.rem / .soap) is not portable. Transparent proxies are a CLR feature unavailable on CoreCLR. These endpoints should be replaced with Web API.
  • Mobile Controls (System.Web.Mobile) require a rewrite. They were deprecated many years ago, and there is no implementation available to port.
  • MVC remains MVC 4, not ASP.NET Core MVC. Features such as Tag Helpers and View Components are unavailable, although attribute routing and @await are supported.
  • Custom ServiceHostFactory implementations inside .svc files are not supported because CoreWCF constructs the service host.
  • Third-party server controls compiled against Microsoft's strong-named System.Web assembly cannot be loaded. They must be recompiled or their source code must be available.
  • Out-of-process session data cannot be shared with existing StateServer or ASPState instances. Types that previously worked only because InProc session avoided serialization will now be validated.
  • <system.webServer> configuration that depends on IIS-native modules must be rewritten as ASP.NET Core middleware or classic <httpModules>.

How Well Is It Tested?
The port includes 445 tests across fifteen projects.
These are not isolated unit tests.
The functional test suites:

  • Start a real Kestrel server.
  • Execute requests using a real HttpClient.
  • Drive browser scenarios through Playwright using Chromium.
  • Click buttons and execute real postbacks.
  • Validate rendered controls and validators.

Additional test suites verify:

  • VB.NET runtime compilation
  • MVC routing and Razor views
  • Web API content negotiation
  • WCF SOAP services through CoreWCF
  • StateServer and SQL Server session state
  • Dynamic Data scaffolding over HTTP

Conclusion
"Rewrite it" is good advice when time and budget allow. However, many organizations maintain large, stable WebForms and MVC applications where the only real limitation is the platform they run on: .NET Framework, IIS, and Windows. This port removes that dependency. The same pages, controllers, and web.config run under Kestrel on .NET 10 across any platform supported by .NET 10 while benefiting from modern tooling and a supported runtime. The migration becomes a host swap instead of a rewrite—and a host swap is measured in days rather than months.



ASP.NET MVC Hosting - HostForLIFE.eu :: Session Timeouts Causes and Remedies

clock June 24, 2026 09:29 by author Peter

For a while now, I have been investigating ASP.Net Session Timeouts. Those of you who work on web applications have undoubtedly seen unexpected timeouts that cause the application to restart abruptly; frequently, these timeouts seem to happen for no obvious reason.

Here, I offer a quick checklist that could be useful when addressing such problems.

Causes for Session Timeout could vary from:

  • Modification in Machine.Config, Web.Config or Global.asax files
  • Application's bin directory or its contents modified 
  • Antivirus is running on the  .config /.aspx files
  • The number of re-compilations (aspx, ascx or asax) exceeds the limit specified by the <compilation numRecompilesBeforeAppRestart=/> setting in machine.config or web.config  (by default this is set to 15) 
  • The physical path of the virtual directory is modified 
  • The CAS policy is modified
  • Sub-Directories of Application are deleted or renamed

New to ASP.Net 2.0  -The 7th point of Sub directories.  i.e. Whenever you delete or rename a sub-directory of your application, the application domain is recycled, terminating all users' sessions (and the cache, etc). This is a big performance hit. This behavior affects dramatically sites that allow document publishing, to the point where they stop functioning. Imagine a situation where a request creates a thread that goes through sub-directories of the application and deletes / renames them - without knowing about this 2.0 application domain recycling policy, chances are that the worker thread in question will not complete because the domain is recycled and the thread aborted. 

Huge Performance Hit
Above results in recycling of Application Domain. At the next request all assemblies need to be reloaded, the cache including any in-proc session variables etc. are empty causing a big performance hit for the application.
 
Remedies/ solutions
App domain restarts

If you suspect app domain restarts (i.e. your sessions seem to expire without obvious reasons), you will be interested to know when the restarts happen and what's causing them.

In ASP.Net 2.0 add the following element in global web.config file (C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\CONFIG) as a child of the <healthMonitoring><rules> elements:
<healthMonitoring>

      <rules>

<add name="Application Lifetime Events Default"  eventName="Application Lifetime Events"

provider="EventLogProvider"  profile="Default"  minInstances="1" maxLimit="Infinite"

                  minInterval="00:01:00"  custom="" />

       </rules>

</healthMonitoring>

This will log system events that provide the time and the reason of the restart (such as: Application is shutting down. Reason: Configuration changed.)
In ASP.Net 1.1, see

If the timeout error message reads as follows:
"System.Web.HttpException: Request timed out."

Check for  <httpRuntime executionTimeout/> in appication's Web.config file
executionTimeout - Specifies the maximum number of seconds that a request is allowed to execute before being automatically shut down by ASP.NET.

You can change this setting in machine.config to affect all applications on your site, or you can override the settings in your application-specific web.config as follows: 
<system.web>

     <httpRuntime executionTimeout="900" />
</system.web>

Note: This time-out applies only if the debug attribute in the compilation element is False. If the debug attribute is True, to help avoiding application shut-down while you are debugging, do not set this time-out to a large value.

The default values in seconds
In the .NET Framework 2.0 = 110.
In the .NET Framework 1.0 and 1.1= 90.

 
Set the Session timeout in IIS Manager in default website also.
Go to IIS Manager, right click on the virtual directory and choose properties.
Now go to virtual directory tab, click Configuration button.
A dialog box will appears. Choose AppOptions tab. Set the session timeout that u need. This will solve the problem. If you are getting the same problem again then set the same thing for Default WebSite also.
 
Remove the session timeout check in IIS, then the timeout will be read from the web.config.
 
Add following code in the web.config of your application file under <system.web>
<sessionState cookieless="false" timeout="330"/>
 

For random session timeouts, timeout occurring before the value set in sessionstate and idle timeouts, check if the application pool in IIS 6.0 has any 'Memory recycling' values selected and they are set up to some low sizes both for virtual or used memoray. 

Ex-If 200 Mb is set and the application reaches this limit in 5 minutes, the recycle happens and any sessions will be thus killed sooner than expected. See the figure below



ASP.NET MVC Hosting - HostForLIFE.eu :: ASP.NET Core MVC Human Resource Management System

clock June 17, 2026 09:01 by author Peter

Systems for managing human resources (HRMS) are crucial for contemporary businesses. They automate hiring, payroll, personnel records, and attendance. The open-source HRM project shows how to use SQL Server, Entity Framework Core, and ASP.NET Core MVC to create a comprehensive HRMS.

Step 1: Environment Setup

  • Install Visual Studio 2022 with ASP.NET workload.
  • Install SQL Server and SSMS.
  • Clone the repository
  • Open the solution in Visual Studio.
Step 2: Database Configuration
  • Update appsettings.json with your SQL Server connection string.
  • Run EF Core migrations:
Update-Database
  • This creates tables like AspNetUsers, AspNetRoles, Companies, Departments, Designations.

Step 3: Authentication & Roles
  • The project uses ASP.NET Identity.
  • Roles: Admin, HR, Manager, Employee.
  • Login page: /Identity/Account/Login.
  • Debugging tip: Place a breakpoint in Login.cshtml.cs → OnPostAsync() to inspect validation.
Step 4: Admin Module
  • Dashboard → Overview of employees, departments, payroll.
  • Companies → CRUD for company records.
  • Departments → CRUD linked to companies.
  • Designations → CRUD linked to companies.
  • Role Management → Assign roles to users.
Step 5: HR Module
  • Employee Management → Add, edit, delete employees.
  • Attendance → Mark daily attendance.
  • Leave Requests → Approve/reject employee leave.
  • Recruitment → Generate offer letters, onboarding workflows.
Step 6: Manager Module
  • Team Dashboard → View team members and performance.
  • Approve Leave → Approve/reject leave requests.
  • Reports → Attendance and performance reports.
Step 7: Employee Module
  • Profile → View/update personal details.
  • Attendance → Mark attendance.
  • Leave Application → Submit leave requests.
  • Salary Slip → View/download salary slips.
  • Offer Letter → View recruitment documents.
Step 8: Payroll & Reports
  • Payroll Management → Salary calculation, deductions, bonuses.
  • Salary Slips → Generate and export slips.
  • Reports → Attendance, payroll, performance analytics.
Step 9: Deployment
  • Publish to IIS or Azure.
  • Configure connection strings for production.
  • Secure sensitive data with Azure Key Vault or environment variables.
Admin Module – Companies, Departments, Designations
Companies Page

Step 1: Model

public class Company
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int LocId { get; set; }
    public string Address { get; set; }

    public Location Location { get; set; }
    public ICollection<Department> Departments { get; set; }
}

Step 2: Controller
public class CompaniesController : Controller
{
    private readonly ApplicationDbContext _context;
    public CompaniesController(ApplicationDbContext context) => _context = context;

    public async Task<IActionResult> Index()
    {
        var companies = await _context.Companies.Include(c => c.Location).ToListAsync();
        return View(companies);
    }

    public IActionResult Create() => View();

    [HttpPost]
    public async Task<IActionResult> Create(Company company)
    {
        if (ModelState.IsValid)
        {
            _context.Add(company);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
        return View(company);
    }
}


Step 3: View
@model IEnumerable<Company>

<h2>Companies</h2>
<table class="table">
    <tr><th>Name</th><th>Location</th><th>Address</th></tr>
    @foreach (var c in Model)
    {
        <tr>
            <td>@c.Name</td>
            <td>@c.Location.Name</td>
            <td>@c.Address</td>
        </tr>
    }
</table>

Departments Page
Step 1: Model

public class Department
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int CompanyId { get; set; }

    public Company Company { get; set; }
}


Step 2: Controller
public class DepartmentsController : Controller
{
    private readonly ApplicationDbContext _context;
    public DepartmentsController(ApplicationDbContext context) => _context = context;

    public async Task<IActionResult> Index()
    {
        var departments = await _context.Departments.Include(d => d.Company).ToListAsync();
        return View(departments);
    }

    public IActionResult Create() => View();

    [HttpPost]
    public async Task<IActionResult> Create(Department department)
    {
        if (ModelState.IsValid)
        {
            _context.Add(department);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
        return View(department);
    }
}

Step 3: View

@model IEnumerable<Department>

<h2>Departments</h2>
<table class="table">
    <tr><th>Name</th><th>Company</th></tr>
    @foreach (var d in Model)
    {
        <tr>
            <td>@d.Name</td>
            <td>@d.Company.Name</td>
        </tr>
    }
</table>

Designations Page
Step 1: Model

public class Designation
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int CompanyId { get; set; }

    public Company Company { get; set; }
}


Step 2: Controller
public class DesignationsController : Controller
{
    private readonly ApplicationDbContext _context;
    public DesignationsController(ApplicationDbContext context) => _context = context;

    public async Task<IActionResult> Index()
    {
        var designations = await _context.Designations.Include(d => d.Company).ToListAsync();
        return View(designations);
    }

    public IActionResult Create() => View();

    [HttpPost]
    public async Task<IActionResult> Create(Designation designation)
    {
        if (ModelState.IsValid)
        {
            _context.Add(designation);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
        return View(designation);
    }
}


Step 3: View
@model IEnumerable<Designation>

<h2>Designations</h2>
<table class="table">
    <tr><th>Name</th><th>Company</th></tr>
    @foreach (var d in Model)
    {
        <tr>
            <td>@d.Name</td>
            <td>@d.Company.Name</td>
        </tr>
    }
</table>


Employee Model
Define the employee entity with relationships to company, department, and designation:
public class Employee
{
    public int Id { get; set; }
    public string FullName { get; set; }
    public string Email { get; set; }
    public string Phone { get; set; }

    public int CompanyId { get; set; }
    public Company Company { get; set; }

    public int DepartmentId { get; set; }
    public Department Department { get; set; }

    public int DesignationId { get; set; }
    public Designation Designation { get; set; }

    public DateTime JoiningDate { get; set; }
}


Employee Controller
Create an MVC controller to handle CRUD operations:
public class EmployeesController : Controller
{
    private readonly ApplicationDbContext _context;
    public EmployeesController(ApplicationDbContext context) => _context = context;

    // List all employees
    public async Task<IActionResult> Index()
    {
        var employees = await _context.Employees
            .Include(e => e.Company)
            .Include(e => e.Department)
            .Include(e => e.Designation)
            .ToListAsync();
        return View(employees);
    }

    // Create employee
    public IActionResult Create()
    {
        ViewBag.Companies = new SelectList(_context.Companies, "Id", "Name");
        ViewBag.Departments = new SelectList(_context.Departments, "Id", "Name");
        ViewBag.Designations = new SelectList(_context.Designations, "Id", "Name");
        return View();
    }

    [HttpPost]
    public async Task<IActionResult> Create(Employee employee)
    {
        if (ModelState.IsValid)
        {
            _context.Add(employee);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
        return View(employee);
    }

    // Edit employee
    public async Task<IActionResult> Edit(int id)
    {
        var employee = await _context.Employees.FindAsync(id);
        if (employee == null) return NotFound();

        ViewBag.Companies = new SelectList(_context.Companies, "Id", "Name", employee.CompanyId);
        ViewBag.Departments = new SelectList(_context.Departments, "Id", "Name", employee.DepartmentId);
        ViewBag.Designations = new SelectList(_context.Designations, "Id", "Name", employee.DesignationId);

        return View(employee);
    }

    [HttpPost]
    public async Task<IActionResult> Edit(Employee employee)
    {
        if (ModelState.IsValid)
        {
            _context.Update(employee);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
        return View(employee);
    }

    // Delete employee
    public async Task<IActionResult> Delete(int id)
    {
        var employee = await _context.Employees.FindAsync(id);
        if (employee == null) return NotFound();

        _context.Employees.Remove(employee);
        await _context.SaveChangesAsync();
        return RedirectToAction(nameof(Index));
    }
}

Employee Views
Index.cshtml
@model IEnumerable<Employee>

<h2>Employees</h2>
<a asp-action="Create" class="btn btn-primary">Add Employee</a>

<table class="table">
    <tr>
        <th>Name</th><th>Email</th><th>Phone</th>
        <th>Company</th><th>Department</th><th>Designation</th><th>Joining Date</th><th>Actions</th>
    </tr>
    @foreach (var e in Model)
    {
        <tr>
            <td>@e.FullName</td>
            <td>@e.Email</td>
            <td>@e.Phone</td>
            <td>@e.Company.Name</td>
            <td>@e.Department.Name</td>
            <td>@e.Designation.Name</td>
            <td>@e.JoiningDate.ToShortDateString()</td>
            <td>
                <a asp-action="Edit" asp-route-id="@e.Id">Edit</a> |
                <a asp-action="Delete" asp-route-id="@e.Id">Delete</a>
            </td>
        </tr>
    }
</table>


Create.cshtml
@model Employee

<h2>Add Employee</h2>
<form asp-action="Create">
    <div class="form-group">
        <label>Name</label>
        <input asp-for="FullName" class="form-control" />
    </div>
    <div class="form-group">
        <label>Email</label>
        <input asp-for="Email" class="form-control" />
    </div>
    <div class="form-group">
        <label>Phone</label>
        <input asp-for="Phone" class="form-control" />
    </div>
    <div class="form-group">
        <label>Company</label>
        <select asp-for="CompanyId" asp-items="ViewBag.Companies" class="form-control"></select>
    </div>
    <div class="form-group">
        <label>Department</label>
        <select asp-for="DepartmentId" asp-items="ViewBag.Departments" class="form-control"></select>
    </div>
    <div class="form-group">
        <label>Designation</label>
        <select asp-for="DesignationId" asp-items="ViewBag.Designations" class="form-control"></select>
    </div>
    <div class="form-group">
        <label>Joining Date</label>
        <input asp-for="JoiningDate" type="date" class="form-control" />
    </div>
    <button type="submit" class="btn btn-success">Save</button>
</form>




ASP.NET MVC Hosting - HostForLIFE.eu :: Kendo Grid in jQuery with All Relevant ASP.NET MVC Properties

clock May 29, 2026 08:32 by author Peter

When working with large data in web applications, displaying data in a simple HTML table becomes difficult.


We need features like:

  • Paging
  • Sorting
  • Filtering
  • Endless scrolling
  • Searching

To solve this problem, developers use Kendo UI Grid.

Kendo Grid is one of the most popular UI components used in ASP.NET MVC and jQuery applications.

In this article, you will learn:

  • What Kendo Grid is
  • Why we use it
  • Important grid properties
  • Endless scrolling
  • Fetching 50-50 records
  • Real examples with explanation

What is Kendo Grid?
Kendo Grid is a powerful table component provided by Progress Telerik.

It helps display data with advanced features using less code.

Why Use Kendo Grid?

  • Professional UI
  • Easy data handling
  • Built-in paging & filtering
  • Fast development

Step 1: Add Kendo UI Files
<link href="https://kendo.cdn.telerik.com/2024.1.130/styles/kendo.default-v2.min.css" rel="stylesheet" />

<script src="https://kendo.cdn.telerik.com/2024.1.130/js/kendo.all.min.js"></script>


Step 2: Create HTML Div
<div id="grid"></div>

Step 3: Create Grid
$("#grid").kendoGrid({
    dataSource: {
        transport: {
            read: {
                url: "/Home/GetStudents",
                dataType: "json"
            }
        },
        pageSize: 50
    },

    height: 550,

    pageable: true,

    sortable: true,

    filterable: true,

    scrollable: true,

    columns: [
        { field: "StudentId", title: "ID", width: 100 },
        { field: "StudentName", title: "Name" },
        { field: "City", title: "City" }
    ]
});


Output
Grid features:

  • Paging
  • Sorting
  • Filtering
  • Scrollable grid

Important Kendo Grid Properties Explained
pageable
pageable: true
Enables pagination

sortable
sortable: true
Allows column sorting


filterable
filterable: true
Adds filter option

scrollable
scrollable: true
Enables scrolling

groupable
groupable: true
Group data by column

selectable
selectable: true
Select row

resizable
resizable: true
Resize columns

reorderable
reorderable: true
Change column order

editable
editable: true

Enable editing
toolbar
toolbar: ["create"]
Add toolbar buttons

Endless Scrolling in Kendo Grid
What is Endless Scrolling?

Normally grid uses pagination.

But endless scrolling automatically loads more data while scrolling.

This improves user experience.
Example
scrollable: {
    endless: true
}

Full Example with Endless Scrolling
$("#grid").kendoGrid({

    dataSource: {
        transport: {
            read: {
                url: "/Home/GetStudents",
                dataType: "json"
            }
        },

        pageSize: 50,

        serverPaging: true
    },

    height: 500,

    scrollable: {
        endless: true
    },

    sortable: true,

    filterable: true,

    columns: [
        { field: "StudentId", title: "ID" },
        { field: "StudentName", title: "Name" },
        { field: "City", title: "City" }
    ]
});

What Does pageSize: 50 Mean?
pageSize: 50

Grid fetches 50 records at one time.

When user scrolls:

  • Next 50 records load automatically
  • Then next 50 records load

This improves:

  • Performance
  • Speed
  • Memory usage

Server Side Data Fetch Example
Controller
public JsonResult GetStudents(int page, int pageSize)
{
    List<Student> list = new List<Student>();

    for (int i = 1; i <= 500; i++)
    {
        list.Add(new Student
        {
            StudentId = i,
            StudentName = "Student " + i,
            City = "London"
        });
    }

    var data = list.Skip((page - 1) * pageSize).Take(pageSize);

    return Json(data, JsonRequestBehavior.AllowGet);
}


Explanation
Skip((page - 1) * pageSize)

Skips previous records
Take(pageSize)
Fetches only 50 records

Why Use 50-50 Data Fetching?

If database has:

100000 records

Loading all data together makes application slow.

Using:
pageSize: 50
Only 50 records load at a time.

Advantages of Endless Scrolling

  • Faster loading
  • Better performance
  • Smooth user experience
  • Less memory usage

Complete Advanced Grid Example
$("#grid").kendoGrid({

    dataSource: {
        transport: {
            read: {
                url: "/Home/GetStudents",
                dataType: "json"
            }
        },

        pageSize: 50,

        serverPaging: true,
        serverSorting: true,
        serverFiltering: true
    },

    height: 550,

    pageable: true,

    sortable: true,

    filterable: true,

    groupable: true,

    reorderable: true,

    resizable: true,

    selectable: "row",

    scrollable: {
        endless: true
    },

    toolbar: ["search"],

    columns: [
        { field: "StudentId", title: "ID", width: 100 },
        { field: "StudentName", title: "Student Name" },
        { field: "City", title: "City" }
    ]
});



ASP.NET MVC Hosting - HostForLIFE.eu :: Why MVC Is Superior to Web Forms?

clock May 20, 2026 09:01 by author Peter

The Reasons for MVC?
In the field of software development, MVC is a new standard design pattern. It's simple to utilize ASP.NET MVC.Google offers dozens of resources to help us learn how to program and configure the code.However, it is always preferable to begin with Why rather than How.

ASP.NET Web Forms cannot be replaced by ASP.NET MVC.Microsoft offers a different method for creating an application.

ASP.NET Web Form Problems:

  • Complexity:HTML and ASP.NET mark up code are used in a Single Page that's why code become very complex.
  • Tightly Coupled-Aspx page and cs page(code behind file) are tightly coupled.so that we can not work separately.
  • Unwanted Html and Java Script-when we drag and drop the controls then unwanted html and java script is automatically inserted in our code that's why page become heavier and it takes time to load on browser.
  • View state-One of the main problems with ASP.NET web forms is the viewstate mechanism, which takes a lot of bandwidth because it serializes all the form inputs and sends it on post commands.
  • Response Time -for any single events it follows the complete Page Life cycle Events life cycle that's why response time of any ASP.NET application is become more than the MVC application.

Benefits of MVC
Three are several benefits of using MVC are given below.

  • Separation of Concerns -Separation of Concern is one of the core advantages of ASP.NET MVC . The MVC framework provides a clean separation of the UI , Business Logic , Model or Data. On the other hand we can say it provides Sepration of Program logic from the User Interface.
  • More Control-The ASP.NET MVC framework provides more control over the HTML , JavaScript and CSS than the traditional Web Forms.
  • Testability-ASP.NET MVC framework provides better testability of the Web Application and good support for the test driven development too.
  • Lightweight-ASP.NET MVC framework doesn’t use View State and thus reduces the bandwidth of the requests to an extent.
  • Full features of ASP.NET-One of the key advantages of using ASP.NET MVC is that it is built on top of ASP.NET framework and hence most of the features of the ASP.NET like membership providers , roles etc can still be used.


About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Month List

Tag cloud

Sign in