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 :: 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")
});
```}



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: GET, SET The Value From HTML Table In ASP.NET MVC jQuery

clock October 6, 2026 11:59 by author Peter

We are going to create an editable HTML table where we set and get the HTML table row value using Asp.Net MVC.
In this step-by-step walkthrough you will learn the following things.

The article is divided into two parts/sections

 

 

 

  • Send Data From Controller To View -- Bind to HTML Table
  • Receiving HTML Table data client side.

SEND Data to View From Controller, SECTION 1

  • How to fetch the data from Database - SQL Server using Entity Framework?
  • How to send list collection data to View?
  • How to Iterate the List Collection in View?

RECEIVED Table Data Client Side, SECTION 2

  • How to get particular row data with different methods?
  • Why is Method 1 better and more reliable than Method 2?
  • How to get the values of all rows of the HTML table?

Section 1. Start of SEND Data to View From Controller

Default View of Solution Explorer.


tblMembers - Table Structure
USE [MbkTest]
GO

/****** Object:  Table [dbo].[tblMembers]    Script Date: 12-Nov-19 7:33:53 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[tblMembers](
    [MemberID] [int] IDENTITY(1,1) NOT NULL,
      NULL,
      NULL,
    PRIMARY KEY CLUSTERED 
(
    [MemberID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

Table sample data view.

Now right-click on the project and select Add New Item.


Select EF Designer From the Database then click on the NEXT button.


In below dialog box do the following things,

  • Data Source: Microsoft SQL Server.
  • Server Name: Your Sql Server detail.
  • Authentication: As per your SQL server.
  • Select or Enter a database name: Select your database.
  • Click on Test Connection.

Then click on the OK button.


 

Select the Table(s) of your choice.


As you click on the FINISH button edmx file will be generated with a selected table(s).


You can see this in the Solution Explorer window.

Right-click on the CONTROLLERS folder and click on ADD --> CONTROLLER.


Default Actionmethod of HomeControllers.


 

Default View - RouteConfig.cs

As per the above code default ActionResult “Index” is executing. Now we will change ActionResult (action) to “FriendResult”. After changing/updating the following things in RouteConfig.cs our default action method is FriendResult.

Now it's changed to this,

RouteConfig.cs File Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace GetSetHtmlTableValue
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "FriendList", id = UrlParameter.Optional }
            );
        }
    }
}


Now press F5, following,

Now Update the following code to the respective files.

HomeController.cs code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace GetSetHtmlTableValue.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult FriendList()
        {
            // Create Instance of EntityFramework dbContext Class
            MbkTestEntities db = new MbkTestEntities();

            // Get all the friends in list collection.
            var FriendList = db.tblFriends.ToList();

            // Send data to view. In view we generate html table with friend datas.
            return View(FriendList);
        }


        // GET: Home
        public ActionResult Index()
        {
            return View();
        }

        // GET: Home/Details/5
        public ActionResult Details(int id)
        {
            return View();
        }

        // GET: Home/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: Home/Create
        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        // GET: Home/Edit/5
        public ActionResult Edit(int id)
        {
            return View();
        }

        // POST: Home/Edit/5
        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        // GET: Home/Delete/5
        public ActionResult Delete(int id)
        {
            return View();
        }

        // POST: Home/Delete/5
        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}


FriendList.cshtml code
@* Receiving data from Controller *@
@model IEnumerable<tblFriend>

@* Setting Page Title *@
@{
    ViewBag.Title = "Friend List";
}

<style>
    /* CSS for table and input (textbox) */
    table, td, th {
        border: 1px solid black;
    }

    table, tr {
        border-collapse: collapse;
    }

    input[type=text] {
        width: 100%;
    }

    th {
        height: 50px;
        text-align: center;
    }
</style>

<h2>Friend List</h2>

<input type="button" value="Get All Rows Data" class="btngetvalue" />
<table>
    <thead>
        <tr>
            <th>
                FRIEND NAME
            </th>
            <th>
                COMPANY NAME
            </th>
            <th>
                EMAIL ID
            </th>
            <th>
                ACTION TYPE 1
            </th>
            <th>
                ACTION TYPE 2
            </th>
        </tr>
    </thead>

    <tbody>

        @* Loop Entire Friend list and paste data to textbox(input) *@
        @foreach (var item in Model)
        {
            // for ID purpose writing this code
            var friendid = "friend" + Convert.ToString(item.FriendID);

            <input type="hidden" id="@friendid" value="@item.FriendID" />

            <tr class="">
                <td>
                    <input type="text" value="@item.FriendName" name="FriendName" />
                </td>
                <td>
                    <input type="text" value="@item.CompanyName" name="CompanyName" />
                </td>
                <td>
                    <input type="text" value="@item.Email" name="Email" />
                </td>

                @* Html Button onclick calling UPDATEROW which passing parameter of friendid. *@
                <td><input type="button" value="Get Row Value Type 1" class="btnrowvalue1" /></td>
                <td><input type="button" value="Get Row Value Type 2" class="btnrowvalue2" /></td>
            </tr>
        }
    </tbody>

</table>

<label id="allrowsdata"><b>All Row Data Come Here</b></label>


Output

RouteConfig.cs CODE
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace GetSetHtmlTableValue
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "FriendList", id = UrlParameter.Optional }
            );
        }
    }
}


_Layout. cshtml CODE
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    <link href="~/Content/Site.css" rel="stylesheet" type="text/css" />
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" type="text/css" />
    <script src="~/Scripts/modernizr-2.6.2.js"></script>
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script src="~/Scripts/bootstrap.min.js"></script>
</head>
<body>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                </ul>
            </div>
        </div>
    </div>

    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>© @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>

</body>
</html>

HomeController.cs CODE
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace GetSetHtmlTableValue.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult FriendList()
        {
            // Create Instance of EntityFramework dbContext Class
            MbkTestEntities db = new MbkTestEntities();

            // Get all the friends in list collection.
            var FriendList = db.tblFriends.Take(10).ToList();

            // send data to view. In view we generate html table with friend datas.
            return View(FriendList);
        }

        // GET: Home
        public ActionResult Index()
        {
            return View();
        }

        // GET: Home/Details/5
        public ActionResult Details(int id)
        {
            return View();
        }

        // GET: Home/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: Home/Create
        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        // GET: Home/Edit/5
        public ActionResult Edit(int id)
        {
            return View();
        }

        // POST: Home/Edit/5
        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        // GET: Home/Delete/5
        public ActionResult Delete(int id)
        {
            return View();
        }

        // POST: Home/Delete/5
        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}

FriendList.cshtml CODE
@* Receiving data from Controller *@
@model IEnumerable<tblFriend>

@* Setting Page Title *@
@{
    ViewBag.Title = "Friend List";
}

<style>
    /* CSS for table and input (textbox) */
    table, td, th {
        border: 1px solid black;
    }

    table, tr {
        border-collapse: collapse;
    }

    input[type=text] {
        width: 100%;
    }

    th {
        height: 50px;
        text-align: center;
    }
</style>

<script>
    $(document).ready(function () {
        // Get All Rows Value of HTML Value
        $(".btngetvalue").click(function () {
            var address = [];
            $("table tr td input[type='text']").each(function () {
                var textval = $(this).val();
                address.push(textval);
            });
            var wholetabledata = address.toString();
            $("#allrowsdata").text("ALL ROWS DATA: \n\n\n" + wholetabledata);
        });

        // METHOD 1 to get Table Row Value
        // Method 1 is good and reliable than Method 2
        $(".btnrowvalue1").click(function () {
            var tr = $(this).closest('tr');
            var FirstCol = tr.find('input[name="FriendName"]').val();
            var SecondCol = tr.find('input[name="CompanyName"]').val();
            var ThirdCol = tr.find('input[name="Email"]').val();
            alert('Type1 : ' + FirstCol + ' ' + SecondCol + ' ' + ThirdCol);
        });


        // METHOD 2 to get Table Row Value
        $(".btnrowvalue2").click(function () {
            var tr = $(this).closest('tr');
            var FirstCol = tr.find('td:eq(0) input').val();;
            var SecondCol = tr.find('td:eq(1) input').val();
            var ThirdCol = tr.find('td:eq(2) input').val();
            alert('Type2 : ' + FirstCol + ' ' + SecondCol + ' ' + ThirdCol);
        });
    });
</script>

<h2>Friend List</h2>

<input type="button" value="Get All Rows Data" class="btngetvalue" />
<table>
    <thead>
        <tr>
            <th>
                FRIEND NAME
            </th>
            <th>
                COMPANY NAME
            </th>
            <th>
                EMAIL ID
            </th>
            <th>
                ACTION TYPE 1
            </th>
            <th>
                ACTION TYPE 2
            </th>
        </tr>
    </thead>

    <tbody>

        @* Loop Entire Friend list and paste data to textbox(input) *@
        @foreach (var item in Model)
        {
            //for ID purpose writing this code
            var friendid = "friend" + Convert.ToString(item.FriendID);

            <input type="hidden" id="@friendid" value="@item.FriendID" />

            <tr class="">
                <td>
                    <input type="text" value="@item.FriendName" name="FriendName" />
                </td>
                <td>
                    <input type="text" value="@item.CompanyName" name="CompanyName" />
                </td>
                <td>
                    <input type="text" value="@item.Email" name="Email" />
                </td>

                @* Html Button onclick calling UPDATEROW which passing parameter of friendid.*@
                <td><input type="button" value="Get Row Value Type 1" class="btnrowvalue1" /> </td>
                <td><input type="button" value="Get Row Value Type 2" class="btnrowvalue2" /> </td>
            </tr>
        }
    </tbody>

</table>

<label id="allrowsdata"><b>All Row Data Come Here</b></label>


End of Receiving Table Data Client Side.



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