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 :: Building an ASP.NET MVC 5 Website with Custom Bootstrap Templates

clock November 3, 2026 12:09 by author Peter

Recently, I have struggled with a problem of how I would use custom free templates in my ASP.NET MVC project rather than using default ones. Here are the steps in making a beautiful bootstrap site using ASP.NET MVC 5.

Download a free template or you can buy a premium template if you want. For our example, we will be using the free Freelancer template. After downloading, you should get the following files.

Open Visual Studio and create an ASP.NET Web Application.

In configuring, the application must be MVC.
I included Web API because I used them a lot in my application.
The last part is very important, because it’s very hard to add an authentication module once the project has been created, trust me, based on experience.

Once the project has been created, the next thing that we should do is copy the files from our downloaded template to our project. Make sure to overwrite any directories of the same name.

Open the BundleConfig.cs file in the App_Start directory and comment all contents in theRegisterBundles method as shown in the image below:

Now we will modify the Views. In modifying the Views, all you need to do is open the Index.html file included in the template and copy it to the corresponding Views.
The first View that will be modified is the _Layout. cshtml, which is located in the Views\Shared folder. Delete all the content and replace it with the code below.
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <!-- Bootstrap Core CSS -->
    <link href="/css/bootstrap.min.css" rel="stylesheet">
    <!-- Custom CSS -->
    <link href="~/css/freelancer.css" rel="stylesheet">
    <!-- Custom Fonts -->
    <link href="/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">

    <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
    <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <!--[endif]-->
</head>

<body id="page-top" data-spy="scroll" data-target=".navbar-fixed-top">
@RenderBody()
</body>
</html>


Next, is to modify the Index. cshtml, which is located in Views\Home. Delete all the content and replace it with the code below.
<!DOCTYPE  html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <meta name="description" content="" />
        <meta name="author" content="" />

        <title>Freelancer - Start Bootstrap Theme</title>

        <!-- Bootstrap Core CSS - Uses Bootswatch Flatly Theme: http://bootswatch.com/flatly/ -->
        <link href="css/bootstrap.min.css" rel="stylesheet" />

        <!-- Custom CSS -->
        <link href="css/freelancer.css" rel="stylesheet" />

        <!-- Custom Fonts -->
        <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css" />
        <link href="http://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css" />
        <link href="http://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic" rel="stylesheet" type="text/css" />

        <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
        <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
        <!--[if  lt IE 9]>
            <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
            <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
        <![endif]-->
    </head>

    <body id="page-top" class="index">
        <!-- Navigation -->
        <nav class="navbar navbar-default navbar-fixed-top">
            <div class="container">
                <!-- Brand and toggle get grouped for better mobile display -->
                <div class="navbar-header page-scroll">
                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                        <span class="sr-only">Toggle navigation</span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>
                    <a class="navbar-brand" href="#page-top">Start Bootstrap</a>
                </div>

                <!-- Collect the nav links, forms, and other content for toggling -->
                <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
                    <ul class="nav navbar-nav navbar-right">
                        <li class="hidden">
                            <a href="#page-top"></a>
                        </li>
                        <li class="page-scroll">
                            <a href="#portfolio">Portfolio</a>
                        </li>
                        <li class="page-scroll">
                            <a href="#about">About</a>
                        </li>
                        <li class="page-scroll">
                            <a href="#contact">Contact</a>
                        </li>
                    </ul>
                </div>
                <!-- /.navbar-collapse -->
            </div>
            <!-- /.container-fluid -->
        </nav>

        <!-- Header -->
        <header>
            <div class="container">
                <div class="row">
                    <div class="col-lg-12">
                        <img class="img-responsive" src="img/profile.png" alt="" />
                        <div class="intro-text">
                            <span class="name">Start Bootstrap</span>
                            <hr class="star-light" />
                            <span class="skills">Web Developer - Graphic Artist - User Experience Designer</span>
                        </div>
                    </div>
                </div>
            </div>
        </header>

        <!-- Portfolio Grid Section -->
        <section id="portfolio">
            <div class="container">
                <div class="row">
                    <div class="col-lg-12 text-center">
                        <h2>Portfolio</h2>
                        <hr class="star-primary" />
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-4 portfolio-item">
                        <a href="#portfolioModal1" class="portfolio-link" data-toggle="modal">
                            <div class="caption">
                                <div class="caption-content">
                                    <i class="fa fa-search-plus fa-3x"></i>
                                </div>
                            </div>
                            <img src="img/portfolio/cabin.png" class="img-responsive" alt="" />
                        </a>
                    </div>
                    <div class="col-sm-4 portfolio-item">
                        <a href="#portfolioModal2" class="portfolio-link" data-toggle="modal">
                            <div class="caption">
                                <div class="caption-content">
                                    <i class="fa fa-search-plus fa-3x"></i>
                                </div>
                            </div>
                            <img src="img/portfolio/cake.png" class="img-responsive" alt="" />
                        </a>
                    </div>
                    <div class="col-sm-4 portfolio-item">
                        <a href="#portfolioModal3" class="portfolio-link" data-toggle="modal">
                            <div class="caption">
                                <div class="caption-content">
                                    <i class="fa fa-search-plus fa-3x"></i>
                                </div>
                            </div>
                            <img src="img/portfolio/circus.png" class="img-responsive" alt="" />
                        </a>
                    </div>
                    <div class="col-sm-4 portfolio-item">
                        <a href="#portfolioModal4" class="portfolio-link" data-toggle="modal">
                            <div class="caption">
                                <div class="caption-content">
                                    <i class="fa fa-search-plus fa-3x"></i>
                                </div>
                            </div>
                            <img src="img/portfolio/game.png" class="img-responsive" alt="" />
                        </a>
                    </div>
                    <div class="col-sm-4 portfolio-item">
                        <a href="#portfolioModal5" class="portfolio-link" data-toggle="modal">
                            <div class="caption">
                                <div class="caption-content">
                                    <i class="fa fa-search-plus fa-3x"></i>
                                </div>
                            </div>
                            <img src="img/portfolio/safe.png" class="img-responsive" alt="" />
                        </a>
                    </div>
                    <div class="col-sm-4 portfolio-item">
                        <a href="#portfolioModal6" class="portfolio-link" data-toggle="modal">
                            <div class="caption">
                                <div class="caption-content">
                                    <i class="fa fa-search-plus fa-3x"></i>
                                </div>
                            </div>
                            <img src="img/portfolio/submarine.png" class="img-responsive" alt="" />
                        </a>
                    </div>
                </div>
            </div>
        </section>

        <!-- About Section -->
        <section class="success" id="about">
            <div class="container">
                <div class="row">
                    <div class="col-lg-12 text-center">
                        <h2>About</h2>
                        <hr class="star-light" />
                    </div>
                </div>
                <div class="row">
                    <div class="col-lg-4 col-lg-offset-2">
                        <p>Freelancer is a free bootstrap theme created by Start Bootstrap. The download includes the complete source files including HTML, CSS, and JavaScript as well as optional LESS stylesheets for easy customization.</p>
                    </div>
                    <div class="col-lg-4">
                        <p>Whether you're a student looking to showcase your work, a professional looking to attract clients, or a graphic artist looking to share your projects, this template is the perfect starting point!</p>
                    </div>
                    <div class="col-lg-8 col-lg-offset-2 text-center">
                        <a href="#" class="btn btn-lg btn-outline"> <i class="fa fa-download"></i> Download Theme </a>
                    </div>
                </div>
            </div>
        </section>

        <!-- Contact Section -->
        <section id="contact">
            <div class="container">
                <div class="row">
                    <div class="col-lg-12 text-center">
                        <h2>Contact Me</h2>
                        <hr class="star-primary" />
                    </div>
                </div>
                <div class="row">
                    <div class="col-lg-8 col-lg-offset-2">
                        <!-- To configure the contact form email address, go to mail/contact_me.php and update the email address in the PHP file on line 19. -->
                        <!-- The form should work on most web servers, but if the form is not working you may need to configure your web server differently. -->
                        <form name="sentMessage" id="contactForm" novalidate>
                            <div class="row control-group">
                                <div class="form-group col-xs-12 floating-label-form-group controls">
                                    <label>Name</label>
                                    <input type="text" class="form-control" placeholder="Name" id="name" required data-validation-required-message="Please enter your name." />
                                    <p class="help-block text-danger"></p>
                                </div>
                            </div>
                            <div class="row control-group">
                                <div class="form-group col-xs-12 floating-label-form-group controls">
                                    <label>Email Address</label>
                                    <input type="email" class="form-control" placeholder="Email Address" id="email" required data-validation-required-message="Please enter your email address." />
                                    <p class="help-block text-danger"></p>
                                </div>
                            </div>
                            <div class="row control-group">
                                <div class="form-group col-xs-12 floating-label-form-group controls">
                                    <label>Phone Number</label>
                                    <input type="tel" class="form-control" placeholder="Phone Number" id="phone" required data-validation-required-message="Please enter your phone number." />
                                    <p class="help-block text-danger"></p>
                                </div>
                            </div>
                            <div class="row control-group">
                                <div class="form-group col-xs-12 floating-label-form-group controls">
                                    <label>Message</label>
                                    <textarea rows="5" class="form-control" placeholder="Message" id="message" required data-validation-required-message="Please enter a message."></textarea>
                                    <p class="help-block text-danger"></p>
                                </div>
                            </div>
                            <br />
                            <div id="success"></div>
                            <div class="row">
                                <div class="form-group col-xs-12">
                                    <button type="submit" class="btn btn-success btn-lg">Send</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </section>

        <!-- Footer -->
        <footer class="text-center">
            <div class="footer-above">
                <div class="container">
                    <div class="row">
                        <div class="footer-col col-md-4">
                            <h3>Location</h3>
                            <p>
                                3481 Melrose Place<br />
                                Beverly Hills, CA 90210
                            </p>
                        </div>
                        <div class="footer-col col-md-4">
                            <h3>Around the Web</h3>
                            <ul class="list-inline">
                                <li>
                                    <a href="#" class="btn-social btn-outline"><i class="fa fa-fw fa-facebook"></i></a>
                                </li>
                                <li>
                                    <a href="#" class="btn-social btn-outline"><i class="fa fa-fw fa-google-plus"></i></a>
                                </li>
                                <li>
                                    <a href="#" class="btn-social btn-outline"><i class="fa fa-fw fa-twitter"></i></a>
                                </li>
                                <li>
                                    <a href="#" class="btn-social btn-outline"><i class="fa fa-fw fa-linkedin"></i></a>
                                </li>
                                <li>
                                    <a href="#" class="btn-social btn-outline"><i class="fa fa-fw fa-dribbble"></i></a>
                                </li>
                            </ul>
                        </div>
                        <div class="footer-col col-md-4">
                            <h3>About Freelancer</h3>
                            <p>Freelance is a free to use, open source Bootstrap theme created by <a href="http://startbootstrap.com">Start Bootstrap</a>.</p>
                        </div>
                    </div>
                </div>
            </div>
            <div class="footer-below">
                <div class="container">
                    <div class="row">
                        <div class="col-lg-12">
                            Copyright © Your Website 2026
                        </div>
                    </div>
                </div>
            </div>
        </footer>

        <!-- Scroll to Top Button (Only visible on small and extra-small screen sizes) -->
        <div class="scroll-top page-scroll visible-xs visible-sm">
            <a class="btn btn-primary" href="#page-top">
                <i class="fa fa-chevron-up"></i>
            </a>
        </div>

        <!-- Portfolio Modals -->
        <div class="portfolio-modal modal fade" id="portfolioModal1" tabindex="-1" role="dialog" aria-hidden="true">
            <div class="modal-content">
                <div class="close-modal" data-dismiss="modal">
                    <div class="lr">
                        <div class="rl"></div>
                    </div>
                </div>
                <div class="container">
                    <div class="row">
                        <div class="col-lg-8 col-lg-offset-2">
                            <div class="modal-body">
                                <h2>Project Title</h2>
                                <hr class="star-primary" />
                                <img src="img/portfolio/cabin.png" class="img-responsive img-centered" alt="" />
                                <p>
                                    Use this area of the page to describe your project. The icon above is part of a free icon set by
                                    <a href="https://sellfy.com/p/8Q9P/jV3VZ/">Flat Icons</a>. On their website, you can download their free set with 16 icons, or you can purchase the entire set with 146 icons for only $12!
                                </p>
                                <ul class="list-inline item-details">
                                    <li>
                                        Client:
                                        <strong>
                                            <a href="http://startbootstrap.com">Start Bootstrap</a>
                                        </strong>
                                    </li>
                                    <li>
                                        Date:
                                        <strong>
                                            <a href="http://startbootstrap.com">April 2026</a>
                                        </strong>
                                    </li>
                                    <li>
                                        Service:
                                        <strong>
                                            <a href="http://startbootstrap.com">Web Development</a>
                                        </strong>
                                    </li>
                                </ul>
                                <button type="button" class="btn btn-default" data-dismiss="modal"><i class="fa fa-times"></i> Close</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="portfolio-modal modal fade" id="portfolioModal2" tabindex="-1" role="dialog" aria-hidden="true">
            <div class="modal-content">
                <div class="close-modal" data-dismiss="modal">
                    <div class="lr">
                        <div class="rl"></div>
                    </div>
                </div>
                <div class="container">
                    <div class="row">
                        <div class="col-lg-8 col-lg-offset-2">
                            <div class="modal-body">
                                <h2>Project Title</h2>
                                <hr class="star-primary" />
                                <img src="img/portfolio/cake.png" class="img-responsive img-centered" alt="" />
                                <p>
                                    Use this area of the page to describe your project. The icon above is part of a free icon set by
                                    <a href="https://sellfy.com/p/8Q9P/jV3VZ/">Flat Icons</a>. On their website, you can download their free set with 16 icons, or you can purchase the entire set with 146 icons for only $12!
                                </p>
                                <ul class="list-inline item-details">
                                    <li>
                                        Client:
                                        <strong>
                                            <a href="http://startbootstrap.com">Start Bootstrap</a>
                                        </strong>
                                    </li>
                                    <li>
                                        Date:
                                        <strong>
                                            <a href="http://startbootstrap.com">April 2026</a>
                                        </strong>
                                    </li>
                                    <li>
                                        Service:
                                        <strong>
                                            <a href="http://startbootstrap.com">Web Development</a>
                                        </strong>
                                    </li>
                                </ul>
                                <button type="button" class="btn btn-default" data-dismiss="modal"><i class="fa fa-times"></i> Close</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="portfolio-modal modal fade" id="portfolioModal3" tabindex="-1" role="dialog" aria-hidden="true">
            <div class="modal-content">
                <div class="close-modal" data-dismiss="modal">
                    <div class="lr">
                        <div class="rl"></div>
                    </div>
                </div>
                <div class="container">
                    <div class="row">
                        <div class="col-lg-8 col-lg-offset-2">
                            <div class="modal-body">
                                <h2>Project Title</h2>
                                <hr class="star-primary" />
                                <img src="img/portfolio/circus.png" class="img-responsive img-centered" alt="" />
                                <p>
                                    Use this area of the page to describe your project. The icon above is part of a free icon set by
                                    <a href="https://sellfy.com/p/8Q9P/jV3VZ/">Flat Icons</a>. On their website, you can download their free set with 16 icons, or you can purchase the entire set with 146 icons for only $12!
                                </p>
                                <ul class="list-inline item-details">
                                    <li>
                                        Client:
                                        <strong>
                                            <a href="http://startbootstrap.com">Start Bootstrap</a>
                                        </strong>
                                    </li>
                                    <li>
                                        Date:
                                        <strong>
                                            <a href="http://startbootstrap.com">April 2026</a>
                                        </strong>
                                    </li>
                                    <li>
                                        Service:
                                        <strong>
                                            <a href="http://startbootstrap.com">Web Development</a>
                                        </strong>
                                    </li>
                                </ul>
                                <button type="button" class="btn btn-default" data-dismiss="modal"><i class="fa fa-times"></i> Close</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="portfolio-modal modal fade" id="portfolioModal4" tabindex="-1" role="dialog" aria-hidden="true">
            <div class="modal-content">
                <div class="close-modal" data-dismiss="modal">
                    <div class="lr">
                        <div class="rl"></div>
                    </div>
                </div>
                <div class="container">
                    <div class="row">
                        <div class="col-lg-8 col-lg-offset-2">
                            <div class="modal-body">
                                <h2>Project Title</h2>
                                <hr class="star-primary" />
                                <img src="img/portfolio/game.png" class="img-responsive img-centered" alt="" />
                                <p>
                                    Use this area of the page to describe your project. The icon above is part of a free icon set by
                                    <a href="https://sellfy.com/p/8Q9P/jV3VZ/">Flat Icons</a>. On their website, you can download their free set with 16 icons, or you can purchase the entire set with 146 icons for only $12!
                                </p>
                                <ul class="list-inline item-details">
                                    <li>
                                        Client:
                                        <strong>
                                            <a href="http://startbootstrap.com">Start Bootstrap</a>
                                        </strong>
                                    </li>
                                    <li>
                                        Date:
                                        <strong>
                                            <a href="http://startbootstrap.com">April 2026</a>
                                        </strong>
                                    </li>
                                    <li>
                                        Service:
                                        <strong>
                                            <a href="http://startbootstrap.com">Web Development</a>
                                        </strong>
                                    </li>
                                </ul>
                                <button type="button" class="btn btn-default" data-dismiss="modal"><i class="fa fa-times"></i> Close</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="portfolio-modal modal fade" id="portfolioModal5" tabindex="-1" role="dialog" aria-hidden="true">
            <div class="modal-content">
                <div class="close-modal" data-dismiss="modal">
                    <div class="lr">
                        <div class="rl"></div>
                    </div>
                </div>
                <div class="container">
                    <div class="row">
                        <div class="col-lg-8 col-lg-offset-2">
                            <div class="modal-body">
                                <h2>Project Title</h2>
                                <hr class="star-primary" />
                                <img src="img/portfolio/safe.png" class="img-responsive img-centered" alt="" />
                                <p>
                                    Use this area of the page to describe your project. The icon above is part of a free icon set by
                                    <a href="https://sellfy.com/p/8Q9P/jV3VZ/">Flat Icons</a>. On their website, you can download their free set with 16 icons, or you can purchase the entire set with 146 icons for only $12!
                                </p>
                                <ul class="list-inline item-details">
                                    <li>
                                        Client:
                                        <strong>
                                            <a href="http://startbootstrap.com">Start Bootstrap</a>
                                        </strong>
                                    </li>
                                    <li>
                                        Date:
                                        <strong>
                                            <a href="http://startbootstrap.com">April 2026</a>
                                        </strong>
                                    </li>
                                    <li>
                                        Service:
                                        <strong>
                                            <a href="http://startbootstrap.com">Web Development</a>
                                        </strong>
                                    </li>
                                </ul>
                                <button type="button" class="btn btn-default" data-dismiss="modal"><i class="fa fa-times"></i> Close</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="portfolio-modal modal fade" id="portfolioModal6" tabindex="-1" role="dialog" aria-hidden="true">
            <div class="modal-content">
                <div class="close-modal" data-dismiss="modal">
                    <div class="lr">
                        <div class="rl"></div>
                    </div>
                </div>
                <div class="container">
                    <div class="row">
                        <div class="col-lg-8 col-lg-offset-2">
                            <div class="modal-body">
                                <h2>Project Title</h2>
                                <hr class="star-primary" />
                                <img src="img/portfolio/submarine.png" class="img-responsive img-centered" alt="" />
                                <p>
                                    Use this area of the page to describe your project. The icon above is part of a free icon set by
                                    <a href="https://sellfy.com/p/8Q9P/jV3VZ/">Flat Icons</a>. On their website, you can download their free set with 16 icons, or you can purchase the entire set with 146 icons for only $12!
                                </p>
                                <ul class="list-inline item-details">
                                    <li>
                                        Client:
                                        <strong>
                                            <a href="http://startbootstrap.com">Start Bootstrap</a>
                                        </strong>
                                    </li>
                                    <li>
                                        Date:
                                        <strong>
                                            <a href="http://startbootstrap.com">April 2026</a>
                                        </strong>
                                    </li>
                                    <li>
                                        Service:
                                        <strong>
                                            <a href="http://startbootstrap.com">Web Development</a>
                                        </strong>
                                    </li>
                                </ul>
                                <button type="button" class="btn btn-default" data-dismiss="modal"><i class="fa fa-times"></i> Close</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- jQuery -->
        <script src="js/jquery.js"></script>

        <!-- Bootstrap Core JavaScript -->
        <script src="js/bootstrap.min.js"></script>

        <!-- Plugin JavaScript -->
        <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.3/jquery.easing.min.js"></script>
        <script src="js/classie.js"></script>
        <script src="js/cbpAnimatedHeader.js"></script>

        <!-- Contact Form JavaScript -->
        <script src="js/jqBootstrapValidation.js"></script>
        <script src="js/contact_me.js"></script>

        <!-- Custom Theme JavaScript -->
        <script src="js/freelancer.js"></script>
    </body>
</html>


Now run your project. You should get this beautiful page from your local host.




ASP.NET MVC 6 Hosting - HostForLIFE.eu :: ASP.NET MVC Radio Button

clock October 27, 2026 13:53 by author Peter

In ASP.NET MVC, a Radio Button is used when we want the user to select only ONE option from multiple choices.

Example:

  • Select Gender
  • Select Payment Method
  • Select Status (Active/Inactive)

1. What is Radio Button in MVC?
Radio button allows:

  • Only one selection
  • Easy and clear choice

Html Helper:
@Html.RadioButtonFor()

2. Why We Use Radio Button?
We use radio buttons when:

  • Only one option is allowed
  • Fixed choices are available
  • Need simple UI selection

Checkbox = multiple select
Radio Button = single select

3. Static Radio Button (Manual Data)
Model

public class Student
{
    public string Gender { get; set; }
}


View
@model Student

@Html.RadioButtonFor(m => m.Gender, "Male") Male
@Html.RadioButtonFor(m => m.Gender, "Female") Female
@Html.RadioButtonFor(m => m.Gender, "Other") Other

Explanation

  • Same property Gender
  • Only one value selected
  • Selected value will bind automatically

4. Dynamic Radio Button (From SQL Server)
Step 1: Table Example

Gender Table
------------
Id     Name
1      Male
2      Female
3      Other


Step 2: Model
public class Gender
{
    public int Id { get; set; }
    public string Name { get; set; }
}


ViewModel
public class StudentViewModel
{
    public int SelectedGender { get; set; }
    public List<Gender> Genders { get; set; }
}

Step 3: Controller
public ActionResult Create()
{
    StudentViewModel model = new StudentViewModel();

    using (MyDbContext db = new MyDbContext())
    {
        model.Genders = db.Genders.ToList();
    }

    return View(model);
}

Step 4: View
@model StudentViewModel

@foreach (var item in Model.Genders)
{
    <div>
        <input type="radio"
               name="SelectedGender"
               value="@item.Id" /> @item.Name
    </div>
}


Step 5: POST Method
[HttpPost]
public ActionResult Create(StudentViewModel model)
{
    int selectedId = model.SelectedGender;

    return View();
}


Explanation

  • Data comes from database
  • name must be same → only one selection
  • MVC binds selected value automatically

5. Set Selected Radio Button
@Html.RadioButtonFor(m => m.Gender, "Male", new { @checked = "checked" })

OR using model:
model.Gender = "Male";

6. jQuery with Radio Button
Get Selected Value

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<script>
    $("input[name='SelectedGender']").change(function () {
        var value = $(this).val();
        console.log("Selected: " + value);
    });
</script>


Explanation
.change() → triggered when selection changes
.val() → get selected value

7. Custom Radio Button (Static + Dynamic)
View

<div>
    <input type="radio" name="SelectedGender" value="0" /> Select None
</div>

@foreach (var item in Model.Genders)
{
    <div>
        <input type="radio"
               name="SelectedGender"
               value="@item.Id" /> @item.Name
    </div>
}


Explanation

  • First option = static
  • Others = from database

Only one can be selected

8. Important Points

  • Same name is required
  • Use ViewModel for dynamic data
  • Radio button allows single selection
  • Use jQuery for events

9. Common Mistakes

  • Different name for radio buttons
  • Not binding with model
  • Forgetting to set value
  • Using checkbox instead of radio

10. Conclusion
Radio Button is very useful when only one option is required.

You learned:

  • Static radio button
  • Dynamic radio button (SQL Server)
  • jQuery usage
  • Custom radio button


ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Boosting Your ASP.NET Core MVC Project: A Comprehensive Guide to Swagger/OpenAPI API Configuration

clock October 20, 2026 11:28 by author Peter

Modern web development often demands a hybrid approach. While traditional ASP.NET Core MVC projects are famous for rendering server-side HTML views using Razor, many applications also need to expose robust RESTful APIs to power mobile apps, single-page applications (SPAs), or third-party integrations.

When you build APIs, documenting them clearly is just as important as writing the code. This is where Swagger (OpenAPI) comes in. Swagger automatically generates interactive documentation, allowing developers, testers, and clients to explore and test your endpoints directly from a web browser without needing external tools like Postman. In this comprehensive guide, we will walk through setting up Swagger in an ASP.NET Core MVC project step by step.

Why Use Swagger in an MVC Project?
ASP.NET Core MVC naturally handles both MVC controllers (which return views) and API controllers (which return JSON/data). Integrating Swagger into this setup offers several key benefits:

  • Interactive Documentation: Generates a clean UI where users can see endpoints, HTTP methods, request parameters, and response models.
  • Live Testing: Allows you to execute requests directly via the "Try it out" feature.
  • Standards Compliance: Built on the OpenAPI Specification, making it universally recognized across different development tools and ecosystems.

Step 1: Install the Swashbuckle NuGet Package
ASP.NET Core does not include Swagger generation out of the box, but the open-source Swashbuckle.AspNetCore package makes integration seamless. It consists of a Swagger generator, a Swagger document middleware, and a built-in Swagger UI.

Open your terminal, navigate to your project directory, and run the following command:
dotnet add package Swashbuckle.AspNetCore

(Alternatively, you can install it via the NuGet Package Manager UI in Visual Studio by searching for Swashbuckle.AspNetCore).
Step 2: Register Swagger Services in Program.cs

Next, you need to configure the Dependency Injection container in your Program.cs file. Because an MVC project handles both views and API controllers, you want to ensure controller support is enabled alongside the API metadata explorers.

Update your Program.cs file with the following configuration:
var builder = WebApplication.CreateBuilder(args);

// 1. Add services to the container (supports both MVC views and API controllers)
builder.Services.AddControllersWithViews();

// Required to gather metadata for API endpoints
builder.Services.AddEndpointsApiExplorer();

// Register the Swagger generator, defining a Swagger document
builder.Services.AddSwaggerGen(options =>
{
    options.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo
    {
        Title = "My Hybrid ASP.NET Core MVC API",
        Version = "v1",
        Description = "An API documentation guide for my MVC and Web API project."
    });
});

var app = builder.Build();


Step 3: Configure the Middleware Pipeline
Once the services are registered, you must configure the HTTP request pipeline to serve the Swagger JSON file and the interactive UI. It is standard practice to enable Swagger only during development to protect production infrastructure.

Add the following middleware configuration right after building the app:
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI(options =>
    {
        options.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
        
        // Optional: Set RoutePrefix to string.Empty if you want Swagger UI 
        // to load directly at the root URL (e.g., https://localhost:xxxx/)
        // options.RoutePrefix = string.Empty;
    });
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

// Map traditional MVC controller routes (for Razor views)
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

// Map attribute-routed API controllers
app.MapControllers();

app.Run();

Step 4: Create a Sample API Controller

To see Swagger in action, you need an API controller. In ASP.NET Core, API controllers are typically decorated with the [ApiController] attribute and inherit from ControllerBase (unlike MVC controllers which inherit from Controller and return views).

Create a new file named ProductsController.cs inside your Controllers folder:
using Microsoft.AspNetCore.Mvc;

namespace YourProjectName.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ProductsController : ControllerBase
    {
        // GET: api/products
        [HttpGet]
        public IActionResult GetAllProducts()
        {
            var products = new[]
            {
                new { Id = 1, Name = "Mechanical Keyboard", Price = 89.99 },
                new { Id = 2, Name = "Wireless Mouse", Price = 45.50 },
                new { Id = 3, Name = "UltraWide Monitor", Price = 399.00 }
            };

            return Ok(products);
        }

        // GET: api/products/5
        [HttpGet("{id}")]
        public IActionResult GetProductById(int id)
        {
            return Ok(new { Id = id, Name = $"Product Sample {id}", Price = 99.99 });
        }
    }
}


Step 5: Run and Test Your API

  • Build and run your application using dotnet run or by pressing F5 in Visual Studio.
  • Open your web browser and navigate to your application's base URL followed by /swagger (for example, https://localhost:5001/swagger).
  • You will be greeted by the Swagger UI interface, listing your Products controller along with its GET endpoints.
  • Click on an endpoint, hit Try it out, and click Execute to see live JSON responses returned directly from your application.

Pro-Tips for Production-Ready Swagger
As your project grows, you can take your Swagger implementation further with these best practices:

  • XML Comments: Enable XML documentation documentation in your .csproj file and configure Swagger to read it so that code summaries and method descriptions appear in the UI.
  • JWT Authentication: Add security definitions to AddSwaggerGen so developers can input bearer tokens and test secure endpoints directly inside Swagger UI.
  • Multiple Versions: Use Swagger to manage multiple API versions (v1, v2) seamlessly as your application evolves.


ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Select2 Dropdown in ASP.NET MVC

clock October 14, 2026 13:56 by author Peter

In many web applications, we use dropdown lists. But normal dropdowns have limitations like:

  • No search option
  • Poor UI
  • Difficult for large data

To solve this, we use Select2.
Select2 is a powerful jQuery-based plugin that converts normal dropdowns into searchable and user-friendly dropdowns.

In this article, you will learn:

  • What Select2 is
  • Why we use it
  • How to use Select2 in ASP.NET MVC
  • Real example with code

What is Select2?
Select2 is a JavaScript plugin that enhances elements.

It provides:

  • Search inside dropdown
  • Multi-select option
  • Better UI
  • AJAX support

Why Use Select2?

  • Easy to use
  • Works with large data
  • Clean design
  • Improves user experience

Step 1: Add Select2 Files
Add CDN links in your view:
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>


Step 2: Create Dropdown in View
<select id="city" class="form-control">
    <option value="">--Select City--</option>
    <option value="1">Ahmedabad</option>
    <option value="2">Surat</option>
    <option value="3">Rajkot</option>
</select>


Step 3: Apply Select2
<script>
    $(document).ready(function () {
        $("#city").select2();
    });
</script>

Multi-Select Example
<select id="cities" multiple class="form-control">
    <option value="1">Ahmedabad</option>
    <option value="2">Surat</option>
    <option value="3">Rajkot</option>
</select>

$("#cities").select2();

Placeholder Example

$("#city").select2({
    placeholder: "Select City",
    allowClear: true
});


AJAX Data Load Example
Controller

public JsonResult GetCities(string term)
{
    var list = new List<object>
    {
        new { id = 1, text = "Ahmedabad" },
        new { id = 2, text = "Surat" },
        new { id = 3, text = "Rajkot" }
    };

    return Json(list, JsonRequestBehavior.AllowGet);
}

View
$("#city").select2({
    ajax: {
        url: '/Home/GetCities',
        dataType: 'json',
        delay: 250,
        data: function (params) {
            return {
                term: params.term
            };
        },
        processResults: function (data) {
            return {
                results: data
            };
        }
    }
});


Tagging (Custom Input)
$("#city").select2({
    tags: true
});


User can type new values
Set Selected Value
$("#city").val("1").trigger("change");

Common Problems & Solutions
Problem: Not Working

  • Check jQuery loaded
  • Check Select2 files

Problem: Dropdown inside Modal
$("#city").select2({
    dropdownParent: $("#myModal")
});
```}



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