Meet The Author

I'm Ethan Jackson, An 25 years old blogger Currently living in London, United Kingdom. I'm a Skilled Blogger, Part Time web Developer And Creating new things as a web Designer.

author

Blazor WebAssembly and ASP.NET Core Share Authentication

Leave a Comment

A crucial component of creating contemporary online applications is authentication. The majority of apps must safeguard sensitive data, manage login sessions, identify users, and restrict access to various functions.

Typically, ASP.NET Core Identity, cookie authentication, or an external identity provider are used to manage authentication in an ASP.NET Core application. However, developers must ensure that both components of the application operate with the same authorised user when a Blazor WebAssembly frontend connects with an ASP.NET Core backend.

 

This creates an important architectural question: How can a Blazor WebAssembly application share authentication with an ASP.NET Core API without implementing separate login systems?

The answer depends on how the application is hosted, how authentication is configured, and how the browser communicates with the backend.

In this article, we will explore how authentication works between Blazor WebAssembly and ASP.NET Core, understand cookie-based and token-based approaches, implement a practical authentication flow, and discuss security considerations for production applications.

Understanding Authentication Between Blazor WebAssembly and ASP.NET Core

Blazor WebAssembly applications execute inside the browser, while ASP.NET Core APIs execute on the server.

Because these applications run in different execution environments, they do not automatically share authentication state.

For example, imagine an employee management application with the following architecture:

  • Blazor WebAssembly handles the user interface.

  • ASP.NET Core Web API handles business operations.

  • ASP.NET Core Identity manages user accounts.

  • SQL Server stores user and application information.

When a user signs in, the backend establishes an authenticated session. However, the Blazor application also needs to understand whether the user is authenticated so it can display the appropriate pages, navigation options, and actions.

There are two important responsibilities here:

  1. The backend must authenticate requests and enforce authorization.

  2. The Blazor application must display the correct authentication state to the user.

These responsibilities are related, but they are not the same.

A Blazor component showing an authenticated user does not prove that the backend has authorized that user. Every protected API endpoint must perform its own authentication and authorization checks.

Understanding Different Authentication Approaches

There are multiple ways to share authentication between Blazor WebAssembly and ASP.NET Core.

The correct approach depends on whether the frontend and backend share the same origin and whether an external identity provider is involved.

Cookie-Based Authentication

Cookie authentication is a practical option when Blazor WebAssembly and ASP.NET Core are hosted under the same origin.

When a user signs in, the ASP.NET Core backend creates an authentication cookie and sends it to the browser.

The browser stores the cookie and automatically includes it in eligible requests to the same origin.

The ASP.NET Core application validates the cookie and identifies the user.

For example:

Blazor WebAssembly
        |
        | Login Request
        |
        v
ASP.NET Core API
        |
        | Validate Credentials
        |
        v
Authentication Cookie
        |
        v
Browser Stores Cookie
        |
        v
Future API Requests
        |
        v
ASP.NET Core Validates Cookie

This approach avoids exposing authentication tokens directly to JavaScript.

For browser-based applications, cookie authentication is generally a good choice when the application can use a secure same-origin architecture.

Token-Based Authentication

Token-based authentication is another approach, particularly when an application communicates with APIs hosted on separate origins or uses an external identity provider.

The user authenticates through an identity provider, and the application obtains an access token.

The Blazor application sends the token in the Authorization header when calling protected APIs.

For example:

GET /api/products HTTP/1.1
Host: api.example.com
Authorization: Bearer ACCESS_TOKEN

The backend validates the token and checks the user's permissions.

For production applications, OAuth 2.0 and OpenID Connect are preferred standards for this architecture.

Blazor WebAssembly supports authentication through the Microsoft.AspNetCore.Components.WebAssembly.Authentication library and OpenID Connect providers.

Comparing Cookie and Token Authentication

Feature

Cookie Authentication

Token Authentication

Authentication storage

Browser-managed cookie

Access token

Request handling

Browser sends eligible cookies automatically

Application sends bearer token

JavaScript access

HttpOnly cookies are not accessible to JavaScript

Depends on token storage

CSRF protection

Required for state-changing requests

Bearer-token requests require different CSRF considerations

Cross-origin configuration

Requires careful cookie and CORS configuration

Requires appropriate CORS and token configuration

Best suited for

Same-origin browser applications

API-based and distributed architectures

For a same-origin Blazor application, cookie authentication is often simpler. For applications using multiple APIs and external identity providers, token-based authentication may be more appropriate.

Implementing Cookie Authentication Between Blazor WebAssembly and ASP.NET Core

Let's build a practical example using ASP.NET Core as the authentication authority and Blazor WebAssembly as the frontend.

Assume that the backend already has an ASP.NET Core Identity implementation responsible for validating user credentials.

We will use cookie authentication to maintain the user session.

Step 1: Configure Cookie Authentication in ASP.NET Core

Open the backend application's Program.cs file.

Configure authentication and authorization services:

using Microsoft.AspNetCore.Authentication.Cookies;

var builder = WebApplication.CreateBuilder(args);

builder.Services
    .AddAuthentication(
        CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
        options.Cookie.Name = "Application.Auth";

        options.Cookie.HttpOnly = true;

        options.Cookie.SecurePolicy =
            CookieSecurePolicy.Always;

        options.Cookie.SameSite =
            SameSiteMode.Lax;

        options.LoginPath = "/account/login";

        options.ExpireTimeSpan =
            TimeSpan.FromMinutes(30);

        options.SlidingExpiration = true;

        options.Events.OnRedirectToLogin = context =>
        {
            context.Response.StatusCode = 401;

            return Task.CompletedTask;
        };

        options.Events.OnRedirectToAccessDenied = context =>
        {
            context.Response.StatusCode = 403;

            return Task.CompletedTask;
        };
    });

builder.Services.AddAuthorization();

builder.Services.AddControllers();

var app = builder.Build();

app.UseHttpsRedirection();

app.UseAuthentication();

app.UseAuthorization();

app.MapControllers();

app.Run();

Let's understand some important settings.

Cookie.Name defines the authentication cookie name.

HttpOnly prevents JavaScript from reading the cookie directly.

SecurePolicy ensures that the cookie is transmitted over HTTPS.

SameSite controls when the browser sends the cookie in cross-site requests.

ExpireTimeSpan defines the authentication ticket lifetime.

The redirect event configuration is also important for APIs. Instead of redirecting an API request to an HTML login page, the application returns an HTTP 401 response.

This example demonstrates cookie configuration. In an application already using ASP.NET Core Identity, configure the existing Identity application cookie rather than registering a competing authentication scheme.

Step 2: Create a Login Endpoint

The backend needs an endpoint that authenticates the user and establishes the session.

When using ASP.NET Core Identity, the login operation should validate credentials through the configured SignInManager.

A simplified controller example is shown below:

using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/account")]
public class AccountController : ControllerBase
{
    private readonly SignInManager<ApplicationUser>
        _signInManager;

    public AccountController(
        SignInManager<ApplicationUser> signInManager)
    {
        _signInManager = signInManager;
    }

    [HttpPost("login")]
    public async Task<IActionResult> Login(
        LoginRequest request)
    {
        var result = await _signInManager.PasswordSignInAsync(
            request.Email,
            request.Password,
            request.RememberMe,
            lockoutOnFailure: true);

        if (!result.Succeeded)
        {
            return Unauthorized(
                new { Message = "Invalid login credentials." });
        }

        return Ok(new
        {
            Message = "Login successful."
        });
    }
}

public record LoginRequest(
    string Email,
    string Password,
    bool RememberMe);

The PasswordSignInAsync method validates the supplied credentials and establishes the authentication session when the login succeeds.

The authentication cookie is generated by the configured Identity cookie scheme.

In production, also handle account lockout, email confirmation, two-factor authentication, and antiforgery protection.

Step 3: Configure HttpClient in Blazor WebAssembly

The Blazor application needs to communicate with the backend API.

Register HttpClient in the client project's Program.cs file:

using Microsoft.AspNetCore.Components.WebAssembly.Hosting;

var builder = WebAssemblyHostBuilder.CreateDefault(args);

builder.Services.AddScoped(sp =>
    new HttpClient
    {
        BaseAddress = new Uri(
            builder.HostEnvironment.BaseAddress)
    });

await builder.Build().RunAsync();

This example assumes that the frontend and backend share the same origin.

When the browser sends same-origin HTTP requests, eligible authentication cookies are included automatically.

For a separate API origin, configure the API base address and browser credentials appropriately. The backend must also use an explicit CORS policy that allows the frontend origin and credentials.

Step 4: Create an Authentication State Provider

The Blazor application needs to know whether the current user is authenticated.

For this purpose, Blazor provides the AuthenticationStateProvider abstraction.

We can create a custom provider that retrieves the current user's authentication information from the backend.

First, create a response model:

public class UserInfo
{
    public bool IsAuthenticated { get; set; }

    public string? Name { get; set; }

    public List<string> Roles { get; set; } = new();
}

Next, create a protected backend endpoint:

[Authorize]
[HttpGet("me")]
public IActionResult GetCurrentUser()
{
    return Ok(new UserInfo
    {
        IsAuthenticated = true,

        Name = User.Identity?.Name,

        Roles = User.Claims
            .Where(c => c.Type == ClaimTypes.Role)
            .Select(c => c.Value)
            .ToList()
    });
}

The endpoint returns information about the currently authenticated user.

Now create a custom authentication state provider in the Blazor WebAssembly project:

using Microsoft.AspNetCore.Components.Authorization;
using System.Security.Claims;
using System.Net.Http.Json;

public class CustomAuthenticationStateProvider
    : AuthenticationStateProvider
{
    private readonly HttpClient _httpClient;

    public CustomAuthenticationStateProvider(
        HttpClient httpClient)
    {
        _httpClient = httpClient;
    }

    public override async Task<AuthenticationState>
        GetAuthenticationStateAsync()
    {
        try
        {
            var userInfo = await _httpClient
                .GetFromJsonAsync<UserInfo>("api/account/me");

            if (userInfo == null ||
                !userInfo.IsAuthenticated)
            {
                return AnonymousState();
            }

            var claims = new List<Claim>
            {
                new Claim(
                    ClaimTypes.Name,
                    userInfo.Name ?? string.Empty)
            };

            claims.AddRange(userInfo.Roles.Select(role =>
                new Claim(ClaimTypes.Role, role)));

            var identity = new ClaimsIdentity(
                claims,
                "ServerAuthentication");

            return new AuthenticationState(
                new ClaimsPrincipal(identity));
        }
        catch
        {
            return AnonymousState();
        }
    }

    private static AuthenticationState AnonymousState()
    {
        return new AuthenticationState(
            new ClaimsPrincipal(
                new ClaimsIdentity()));
    }

    public void NotifyAuthenticationChanged(
        ClaimsPrincipal user)
    {
        NotifyAuthenticationStateChanged(
            Task.FromResult(
                new AuthenticationState(user)));
    }
}

This provider requests the current user information from the backend and creates a ClaimsPrincipal for the Blazor interface.

Register the provider in Program.cs:

using Microsoft.AspNetCore.Components.Authorization;

builder.Services.AddAuthorizationCore();

builder.Services.AddScoped<
    AuthenticationStateProvider,
    CustomAuthenticationStateProvider>();

The provider allows Blazor components to display the current authentication state.

Importantly, the ClaimsPrincipal created inside WebAssembly is only a representation of the user for the client interface. It does not authenticate API requests or replace backend authorization.

The backend remains responsible for validating the authentication cookie on every protected request.

Step 5: Display Authentication Information in Blazor

Blazor provides the AuthorizeView component to display content based on the authentication state.

For example:

<AuthorizeView>
    <Authorized>
        <h3>Welcome, @context.User.Identity?.Name</h3>

        <p>You are successfully authenticated.</p>
    </Authorized>

    <NotAuthorized>
        <p>Please sign in to continue.</p>
    </NotAuthorized>
</AuthorizeView>

The component automatically displays the appropriate content based on the authentication state provider.

This makes it easier to build navigation menus, dashboards, and protected user interface sections.

However, hiding a button or page section does not protect the corresponding backend operation. The API must still enforce authorization independently.

Handling Logout and Session Expiration

Authentication is not complete without a proper logout process.

When a user logs out, the backend must invalidate the authentication session by removing the authentication cookie.

For cookie-based authentication, a logout endpoint can use the configured authentication scheme:

[HttpPost("logout")]
public async Task<IActionResult> Logout()
{
    await HttpContext.SignOutAsync(
        CookieAuthenticationDefaults.AuthenticationScheme);

    return Ok(new
    {
        Message = "Logged out successfully."
    });
}

After the backend clears the cookie, the Blazor application should refresh its authentication state.

For example, the custom provider can notify components that the user is now anonymous.

The application should also handle expired sessions. If an API request returns HTTP 401, the frontend can refresh the authentication state and redirect the user to the login page when appropriate.

Logout and other state-changing endpoints should be protected against cross-site request forgery.

Important Security Considerations for Production

Sharing authentication between Blazor WebAssembly and ASP.NET Core requires careful security configuration.

Use HTTPS Everywhere

Authentication cookies and other sensitive information should never be transmitted over unprotected HTTP connections.

Configure HTTPS for both the frontend and backend.

Protect Against CSRF Attacks

Cookie authentication automatically attaches eligible cookies to browser requests.

This creates a CSRF risk for state-changing operations.

Use antiforgery tokens for operations such as login, logout, updating user information, and deleting records. Validate these tokens on the backend.

Never Trust Client-Side Authorization

A user can inspect and modify client-side application code.

Therefore, authorization checks performed inside Blazor components are not sufficient.

Always use the Authorize attribute, authorization policies, or equivalent backend checks on protected endpoints.

Configure Cookie Properties Correctly

Use HttpOnly and Secure cookies, and choose an appropriate SameSite policy.

If the frontend and backend use different origins, review browser credential handling and cross-origin cookie restrictions carefully.

Handle Session Expiration

Applications should have a clear session expiration strategy.

Handle expired sessions gracefully and avoid leaving users with interfaces that appear authenticated while backend requests are being rejected.

Avoid Storing Sensitive Tokens in Browser Storage

Avoid storing access tokens, refresh tokens, or other sensitive credentials in localStorage or sessionStorage without carefully evaluating the security implications.

For browser-based applications, secure cookies or a properly designed backend-for-frontend architecture can reduce direct exposure of credentials to JavaScript.

Common Mistakes and Troubleshooting

Problem

Possible Cause

Recommended Solution

Blazor shows the user as anonymous

Authentication provider cannot retrieve user information

Verify the current-user API endpoint

API returns HTTP 401

Missing, expired, or invalid authentication cookie

Check cookie configuration and browser requests

API returns HTTP 403

User lacks the required permission

Review roles and authorization policies

Login succeeds but API calls fail

Cookie is not included in subsequent requests

Verify origin, cookie properties, and credentials

Authentication disappears after refresh

Client-only authentication state was not restored

Retrieve the session from the backend

Logout does not update the interface

Authentication state was not refreshed

Notify the authentication state provider

Cross-origin login fails

Incorrect CORS or cookie configuration

Configure explicit origins and credentials

Browser developer tools are particularly useful when troubleshooting authentication issues.

Inspect the Network tab to verify whether the login response contains the expected Set-Cookie header and whether subsequent API requests include the authentication cookie.

Also inspect the browser console for CORS errors and review backend authentication logs.

Summary

Sharing authentication between Blazor WebAssembly and ASP.NET Core requires a clear separation between client-side authentication state and server-side security enforcement.

Cookie authentication is a practical choice when both applications share the same origin. It allows the browser to manage the authentication cookie while ASP.NET Core validates incoming requests.

Token-based authentication is another option when applications communicate with separate APIs or use external identity providers.

Blazor's AuthenticationStateProvider and AuthorizeView components make it easier to display authentication information in the user interface. However, these components should never replace backend authentication and authorization checks.

For production applications, developers should focus on HTTPS, secure cookie configuration, CSRF protection, session expiration, and proper API authorization.

With the right architecture, Blazor WebAssembly and ASP.NET Core can share a consistent authentication experience without creating separate and unnecessary authentication systems.

Windows Hosting Recommendation

HostForLIFE.eu receives Spotlight standing advantage award for providing recommended, cheap and fast ecommerce Hosting including the latest Magento. From the leading technology company, Microsoft. All the servers are equipped with the newest Windows Server 2025, SQL Server 2025, ASP.NET Core 11, ASP.NET MVC 6.0, Silverlight 5, WebMatrix and Visual Studio Lightswitch. Security and performance are at the core of their Magento hosting operations to confirm every website and/or application hosted on their servers is highly secured and performs at optimum level. mutually of the European ASP.NET hosting suppliers, HostForLIFE guarantees 99.9% uptime and fast loading speed. From €3.49/month , HostForLIFE provides you with unlimited disk space, unlimited domains, unlimited bandwidth,etc, for your website hosting needs.
 
https://hostforlifeasp.net/
Read More

Maintaining Kafka Consumers Throughout Rebalances

Leave a Comment

A typical aspect of managing a consumer group is Kafka consumer rebalancing. It occurs when members join or depart the organization, when divisions are redistributed, or when the group must bounce back from a setback.

 
When rebalances occur too frequently, the issue arises. It is possible for a customer to do beneficial tasks for a brief period of time before losing their division assignment. While the group decides on a new task, messages may be processed once more, consumption may stop, and latency may increase.

Frequent rebalancing can become a performance and reliability issue for applications handling high event quantities.

Eliminating rebalancing is not the aim. It is necessary for Kafka to preserve partition ownership and consumer group membership. The objective is to stop regular application work from creating needless group instability and to make consumer behaviour predictable during rebalances.

This article describes why Kafka consumers rebalance, what leads to preventable rebalances, and how to create a C# consumer that properly manages them. 

What Is a Kafka Consumer Rebalance?

Kafka divides a topic into partitions.

For example:

orders
├── Partition 0
├── Partition 1
├── Partition 2
└── Partition 3

A consumer group processes those partitions.

With two consumers:

Consumer A -> Partition 0, Partition 1
Consumer B -> Partition 2, Partition 3

If Consumer B leaves the group, Kafka needs to redistribute its partitions.

Consumer A -> Partition 0, Partition 1, Partition 2, Partition 3

That redistribution is a rebalance.

A rebalance can happen when:

  • A new consumer joins the group.

  • A consumer shuts down.

  • A consumer crashes.

  • A consumer misses group heartbeats.

  • Partition assignments change.

  • A consumer takes too long between polls.

  • Deployment replaces consumer instances.

  • Group membership changes.

Rebalancing itself is expected behavior.

The problem is frequent or poorly handled rebalancing.

Why Rebalances Can Affect Application Performance

During a rebalance, partition ownership changes.

A simplified sequence looks like this:

Consumer A
    |
    | Processing
    v
Kafka detects membership change
    |
    v
Rebalance starts
    |
    v
Partition ownership changes
    |
    v
Consumers resume processing

Depending on the consumer configuration and assignment strategy, consumption can pause during this process.

If the application is already under heavy load, even a short pause can increase consumer lag.

Repeated rebalances can create a cycle:

Slow processing
      |
      v
Consumer misses expected timing
      |
      v
Rebalance
      |
      v
Consumption pauses
      |
      v
Lag increases
      |
      v
More work accumulates
      |
      v
Consumer becomes slower
      |
      v
Another rebalance

This is why consumer stability matters as much as raw processing speed.

The Most Common Cause Is Consumer Timing

Kafka needs to know that a consumer is still participating in the group.

Two timing concepts are especially important:

  • Heartbeat behavior

  • Poll interval

The exact configuration depends on the Kafka client and workload, but the underlying principle is simple.

The consumer must continue communicating with Kafka while processing records.

A consumer that spends too long doing synchronous work without polling can be considered unhealthy.

For example:

Poll
 |
 v
Process 10,000 records
 |
 | 10 minutes
 v
Poll again

If the processing interval exceeds the configured limits, Kafka may remove the consumer from the group.

The result is a rebalance.

Separate Polling From Slow Business Work

One of the most useful design improvements is separating Kafka consumption from slow business processing.

Instead of making the Kafka consumer directly perform a long-running operation:

Kafka Consumer
     |
     v
Database
     |
     v
External API
     |
     v
Large computation

use a controlled processing pipeline:

Kafka Consumer
     |
     v
Bounded Work Queue
     |
     +---- Worker 1
     +---- Worker 2
     +---- Worker 3

The consumer can continue participating in the group while workers process the application workload.

However, this design introduces another responsibility.

You must not allow the internal queue to grow without limits.

A bounded queue provides backpressure.

Using a Bounded Channel in C#

The .NET Channel<T> class works well for this type of pipeline.

For example:

var channel = Channel.CreateBounded<OrderEvent>(
    new BoundedChannelOptions(500)
    {
        FullMode = BoundedChannelFullMode.Wait,
        SingleWriter = true,
        SingleReader = false
    });

The Kafka consumer writes records into the channel:

await channel.Writer.WriteAsync(
    orderEvent,
    cancellationToken);

Worker tasks can then process the events:

await foreach (var orderEvent in
    channel.Reader.ReadAllAsync(cancellationToken))
{
    await ProcessOrderAsync(
        orderEvent,
        cancellationToken);
}

The bounded capacity prevents Kafka consumption from creating unlimited in-memory work.

Do Not Process Unlimited Records in Parallel

A common response to consumer lag is increasing concurrency.

For example:

Consumer
   |
   +--> Task 1
   +--> Task 2
   +--> Task 3
   +--> ...
   +--> Task 1000

This can make the problem worse.

If every task performs a database query, the application may overwhelm the database.

If every task calls an external API, the API may throttle the application.

If memory usage increases, the process can become unstable.

A better design uses controlled concurrency:

Kafka Consumer
      |
      v
Bounded Queue
      |
      +--> Worker 1
      +--> Worker 2
      +--> Worker 3
      +--> Worker 4

The correct number of workers should be based on the workload and downstream capacity.

Understand max.poll.interval.ms

Kafka clients expose a configuration that controls the maximum interval between polls.

If your consumer performs too much work between polls, it can exceed this interval.

For a .NET Kafka client, the configuration may look like:

var config = new ConsumerConfig
{
    BootstrapServers = bootstrapServers,
    GroupId = "orders-service",
    AutoOffsetReset = AutoOffsetReset.Earliest,
    EnableAutoCommit = false,
    MaxPollIntervalMs = 300000
};

The important point is not to simply increase the value whenever rebalances occur.

If processing genuinely takes longer, you should first understand why.

Increasing the interval can hide an underlying performance problem.

For example:

Database query = 2 seconds
Message processing = 3 seconds
External API = 8 seconds
Total = 13 seconds

If the consumer processes many records in one poll before polling again, the total time can become much larger than expected.

Reduce the Amount of Work Per Poll

Another useful configuration is the maximum number of records returned in one poll.

For example:

var config = new ConsumerConfig
{
    BootstrapServers = bootstrapServers,
    GroupId = "orders-service",
    MaxPollIntervalMs = 300000,
    MaxPollRecords = 100
};

If processing each record takes time, reducing the number of records processed per polling cycle can help keep the consumer responsive.

The right value depends on:

  • Processing time per record

  • Database capacity

  • External API latency

  • Consumer CPU usage

  • Message size

  • Desired throughput

There is no universal value that works for every application.

Offset Commit Strategy Matters

Kafka consumers need to commit offsets to track progress.

There are two broad concerns:

Message received
      |
      v
Message processed
      |
      v
Offset committed

The order matters.

If an offset is committed before the business operation completes, a crash can result in lost processing.

If the business operation completes but the offset is not committed before a crash, Kafka can deliver the record again.

That second scenario is why consumers should be idempotent.

A safe mental model is:

Process successfully
      |
      v
Commit offset

But even this does not create exactly-once business behavior by itself.

The database operation and Kafka offset commit are separate systems.

Why Duplicate Processing Can Still Happen

Consider this sequence:

1. Kafka delivers message 100
2. Consumer processes message 100
3. Database transaction succeeds
4. Consumer crashes
5. Offset 100 was not committed
6. Kafka delivers message 100 again

The message is processed twice.

This is normal for at-least-once processing.

The application should make important operations idempotent.

For example:

eventId = 7b8e...

First processing
    -> Database change
    -> Record eventId

Duplicate processing
    -> eventId already exists
    -> Skip business operation

This is particularly important when rebalances are frequent.

Cooperative Rebalancing Can Reduce Disruption

Kafka supports different partition assignment approaches.

Some strategies can move many partitions away from consumers during a rebalance.

Cooperative rebalancing allows partition movement to happen more gradually.

With the Confluent Kafka .NET client, the configuration can be selected through the partition assignment strategy.

For example:

var config = new ConsumerConfig
{
    BootstrapServers = bootstrapServers,
    GroupId = "orders-service",
    PartitionAssignmentStrategy =
        PartitionAssignmentStrategy.CooperativeSticky
};

The exact behavior depends on the Kafka client version and broker/client compatibility, so configuration changes should be tested in a staging environment.

The main benefit is reducing unnecessary disruption when membership changes.

Graceful Shutdown Is Important

Consumer deployments often cause rebalances.

If an application shuts down abruptly, Kafka has to detect that the consumer disappeared.

A graceful shutdown allows the consumer to leave the group cleanly.

For example:

await consumer.CloseAsync();

A hosted service can handle application cancellation:

public async Task StopAsync(
    CancellationToken cancellationToken)
{
    _consumer.Close();

    await base.StopAsync(cancellationToken);
}

The exact implementation depends on how the consumer is hosted.

The important idea is that deployment should not look like a consumer crash.

A clean shutdown can reduce unnecessary group disruption.

Be Careful With Deployments

Suppose a consumer group has ten instances.

A rolling deployment replaces them one by one.

If each replacement causes partition movement, the group may experience several rebalances during deployment.

A deployment strategy should therefore consider:

  • Number of consumer instances

  • Partition count

  • Shutdown behavior

  • Startup timing

  • Health checks

  • Readiness checks

  • Maximum unavailable instances

A consumer should not receive production traffic before it is ready to participate correctly in the group.

Static Membership Can Help Stable Consumer Groups

Kafka also supports static group membership.

A stable member identity can reduce unnecessary partition movement when a consumer temporarily restarts.

For example:

var config = new ConsumerConfig
{
    BootstrapServers = bootstrapServers,
    GroupId = "orders-service",
    GroupInstanceId = instanceId
};

The GroupInstanceId should be stable for the intended consumer instance.

This is useful in environments where consumer instances have predictable identities.

It should not be configured casually with the same value on multiple instances.

Two active consumers should not incorrectly claim the same group instance identity.

Watch Out for Long External API Calls

A Kafka consumer can become unstable when message processing depends on slow external services.

For example:

Kafka
  |
  v
Consumer
  |
  v
Payment API
  |
  | 30 seconds
  v
Response

If the consumer processes many records sequentially, the delay can become large.

A better design can move external work into a bounded worker pool or use a workflow architecture appropriate for the operation.

Timeouts are also important:

using var timeoutCts =
    CancellationTokenSource.CreateLinkedTokenSource(
        cancellationToken);

timeoutCts.CancelAfter(
    TimeSpan.FromSeconds(10));

await paymentClient.ProcessAsync(
    payment,
    timeoutCts.Token);

A timeout prevents one dependency from keeping a message-processing task alive indefinitely.

Avoid Blocking Async Code

Blocking calls can make consumer responsiveness worse.

Avoid:

var result = ProcessAsync().Result;

and:

ProcessAsync().Wait();

Prefer:

var result = await ProcessAsync();

This is especially important in consumers because a blocked processing pipeline can increase latency, reduce throughput, and make timing problems harder to diagnose.

Monitor Consumer Lag

Consumer lag is one of the most useful metrics for Kafka applications.

It represents the difference between messages available in the partition and the consumer's current position.

A simplified example:

Partition 0
Latest offset: 10000
Consumer offset: 9800

Lag = 200

A temporary increase is not necessarily a problem.

The important question is whether the consumer can recover.

Lag
 |
 |       /\
 |      /  \
 |_____/    \____
              \
               \____

Healthy consumers can catch up after a short traffic spike.

A struggling consumer might look like:

Lag
 |
 |     /
 |    /
 |   /
 |  /
 | /
 |/____________

If lag keeps increasing, investigate:

  • Processing time

  • Database latency

  • External API latency

  • Consumer CPU

  • Memory pressure

  • Number of workers

  • Partition count

  • Rebalance frequency

Useful Metrics to Monitor

A production Kafka consumer should expose enough information to answer why processing is slowing down.

Useful metrics include:

Metric

What it tells you

Consumer lag

Whether the consumer is keeping up

Rebalance count

Whether group membership is unstable

Processing duration

How long business work takes

Poll interval

Whether the consumer is polling regularly

Error rate

Whether messages are failing

Retry count

Whether downstream operations are unstable

Commit latency

Whether offset commits are delayed

CPU usage

Whether the consumer is resource constrained

Memory usage

Whether buffering is excessive

Database latency

Whether the database is slowing processing

Do not look at consumer lag alone.

A high lag value tells you that the consumer is behind, but not why.

Common Mistakes

Increasing max.poll.interval.ms without fixing processing time

This may hide the problem instead of solving it.

First measure how long message processing actually takes.

Processing everything inside the Kafka callback

Long-running work inside the consumer loop can make polling behavior difficult to control.

A bounded worker pipeline is often easier to operate.

Creating unlimited background tasks

Starting one task per message can move the bottleneck from Kafka to the application or database.

Use bounded concurrency.

Committing offsets too early

If the offset is committed before business processing succeeds, a crash can result in lost work.

Assuming a rebalance means messages are lost

A rebalance changes partition ownership. With appropriate offset management and idempotent processing, messages can be processed safely again.

Ignoring graceful shutdown

Abrupt termination can make deployments look like consumer failures.

Close consumers cleanly when the application stops.

Using the same GroupInstanceId for multiple consumers

Static membership requires unique, stable instance identities.

Duplicate identities can cause membership problems.

A Practical Consumer Design

A production-oriented architecture can look like this:

                  Kafka
                    |
                    v
            Consumer Group
                    |
                    v
             Poll Records
                    |
                    v
          Bounded Work Queue
                    |
          +---------+---------+
          |         |         |
          v         v         v
       Worker    Worker    Worker
          |         |         |
          +---------+---------+
                    |
                    v
          Business Operations
                    |
                    v
             Commit Offset

The important controls are distributed across the pipeline.

Kafka controls partition assignment.

The consumer controls polling.

The bounded queue controls memory and backpressure.

Workers control processing concurrency.

The database or downstream services control transaction and idempotency behavior.

This separation makes the system easier to tune.

When to Increase Consumer Count

Adding more consumers can increase throughput, but only when enough partitions are available.

For example:

Topic partitions = 3
Consumers = 3

Each consumer can receive work.

But:

Topic partitions = 3
Consumers = 10

Seven consumers will remain idle because there are not enough partitions to assign.

Increasing consumer count also changes group membership and can trigger rebalancing.

Scale consumers based on:

  • Partition count

  • Consumer lag

  • Processing time

  • CPU usage

  • Downstream capacity

Do not scale purely because lag increased.

The bottleneck might be the database or an external API.

Production Checklist

Before running a Kafka consumer in production, verify:

  1. Consumer processing time is measured.

  2. Polling is not blocked by long-running operations.

  3. MaxPollIntervalMs matches the actual workload.

  4. MaxPollRecords is tuned appropriately.

  5. Consumer concurrency is bounded.

  6. Backpressure exists between Kafka and workers.

  7. Offsets are committed only after successful processing.

  8. Business operations are idempotent.

  9. Graceful shutdown is implemented.

  10. Rebalance events are monitored.

  11. Consumer lag is monitored.

  12. Database and external API latency are monitored.

  13. Retry behavior is bounded.

  14. Static membership is configured only when appropriate.

  15. Cooperative assignment is tested when suitable.

  16. Deployments are designed to minimize unnecessary consumer disruption.

Advantages and Disadvantages

Advantages

  • More stable consumer groups.

  • Lower impact from normal membership changes.

  • Better control over processing concurrency.

  • Reduced risk of consumer lag caused by slow message handling.

  • Easier troubleshooting through clear processing boundaries.

  • Better protection for downstream databases and APIs.

Disadvantages

  • The architecture becomes more complex.

  • Worker queues require capacity planning.

  • Incorrect concurrency can still overload downstream systems.

  • Rebalance tuning depends on workload characteristics.

  • More metrics and operational monitoring are required.

The objective is not to prevent every rebalance.

A healthy Kafka application should be able to rebalance without turning the event-processing pipeline into an outage.

Conclusion

Kafka rebalancing is part of how consumer groups maintain reliable partition ownership. It becomes a problem when consumers take too long to process records, fail to poll regularly, shut down abruptly, or constantly join and leave the group.

The first step is to understand the processing path rather than immediately changing Kafka timeout values.

Measure how long message processing takes. Keep polling responsive. Limit the amount of work performed in each polling cycle. Use bounded concurrency instead of creating unlimited tasks. Make business operations idempotent so records can safely be processed again when necessary.

Graceful shutdown, cooperative rebalancing, and stable group membership can further reduce unnecessary disruption.

Most importantly, monitor consumer lag and rebalance frequency together with database and external-service latency. A Kafka consumer that appears to have a Kafka problem may actually be waiting on a slow database or API.

A well-designed consumer does not depend on rebalances never happening. It is designed so that when a rebalance does happen, processing can continue without losing messages or overwhelming the systems behind it.

Windows Hosting Recommendation

HostForLIFE.eu receives Spotlight standing advantage award for providing recommended, cheap and fast ecommerce Hosting including the latest Magento. From the leading technology company, Microsoft. All the servers are equipped with the newest Windows Server 2025, SQL Server 2025, ASP.NET Core 11, ASP.NET MVC 6.0, Silverlight 5, WebMatrix and Visual Studio Lightswitch. Security and performance are at the core of their Magento hosting operations to confirm every website and/or application hosted on their servers is highly secured and performs at optimum level. mutually of the European ASP.NET hosting suppliers, HostForLIFE guarantees 99.9% uptime and fast loading speed. From €3.49/month , HostForLIFE provides you with unlimited disk space, unlimited domains, unlimited bandwidth,etc, for your website hosting needs.
 
https://hostforlifeasp.net/
Read More

Making a Console App Faster and Smaller with .NET 11

Leave a Comment

Even though a console application appears straightforward, putting it into production is quite another. Framework dependencies, NuGet packages, configuration files, and runtime components may all add to the deployment footprint of even modest applications.

When deploying command-line tools to numerous servers, cloud environments, containers, or CI/CD agents, this becomes crucial.

Consider a console application that runs every few minutes, processes a file, calls an API, and exits. The actual business logic might take only a few milliseconds, but application startup and deployment overhead can become a noticeable part of its execution time.

.NET provides several ways to address these problems. You can remove unused code through trimming, compile applications ahead of time using Native AOT, and configure publishing to prioritize application size or execution speed.

.NET 11 continues to build on these capabilities.

In this article, we will create a console application, examine its publishing options, and see how to make it smaller and faster without unnecessarily changing the application logic.

Why Does a Small Console Application Need Optimization?

Let's take a simple example.

You have a console application responsible for processing daily transaction files. It starts, reads a file, performs calculations, writes the results, and exits.

The application itself may contain only a few classes, but its published output can include much more than your source code.

Some of the additional components include:

  • .NET runtime libraries.
  • Application dependencies.
  • Third-party NuGet packages.
  • Native libraries.
  • Configuration and supporting files.

The actual deployment size depends on the publishing model, target operating system, architecture, and dependencies.

There are also performance considerations.

If the application starts and exits frequently, startup time matters. If it runs continuously, steady-state execution performance may be more important.

This is why optimization should begin with understanding how the application is used.

Step 1: Create a Basic .NET 11 Console Application

First, create a new console application.

dotnet new console -n FastConsoleApp -f net11.0

cd FastConsoleApp

Open the project file. It should contain a configuration similar to this:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net11.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

</Project>

Now replace the contents of Program.cs with a small processing example.

using System.Diagnostics;

var stopwatch = Stopwatch.StartNew();

Console.WriteLine("Transaction processing started.");

var transactions = new[]
{
    1200.50m,
    2500.00m,
    850.75m,
    4200.00m,
    1750.25m
};

decimal total = transactions.Sum();

stopwatch.Stop();

Console.WriteLine($"Transactions: {transactions.Length}");
Console.WriteLine($"Total Amount: {total}");
Console.WriteLine($"Execution Time: {stopwatch.ElapsedMilliseconds} ms");

This application performs a small calculation and prints the result.

Build and run it:

dotnet build -c Release

dotnet run -c Release

At this point, we have a working application. Next, we will change how it is published.

Step 2: Understand the Different Publishing Options

.NET supports multiple deployment models. Each one makes a different trade-off between deployment size, startup performance, and runtime requirements.

Publishing optionMain purposeImportant consideration
Framework-dependentUses an installed .NET runtimeSmaller application-specific deployment
Self-containedIncludes the required runtimeLarger deployment output
Single-fileBundles application-dependent filesSimplifies distribution
ReadyToRunPrecompiles assembliesCan improve startup but increases size
Native AOTCompiles application code into native machine codeFaster startup and potentially lower memory usage

These options are not interchangeable.

For example, single-file publishing does not automatically make an application faster or smaller. It primarily simplifies distribution.

Native AOT is different because it compiles application code into native machine code during publishing and removes the need for a JIT compiler at runtime.

For a small console application, Native AOT is worth testing.

Step 3: Enable Native AOT

Native AOT is one of the most useful options when your application needs fast startup and does not depend on runtime code generation.

To enable it, update the project file:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net11.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>

    <PublishAot>true</PublishAot>

  </PropertyGroup>

</Project>

The important setting is:

<PublishAot>true</PublishAot>

This tells the .NET SDK to use Native AOT when publishing the application.

Native AOT also enables trimming because the compiler needs to determine which code is required and which code can be removed.

Unlike traditional JIT-based applications, Native AOT does not generate machine code dynamically when the application starts.

Publish the application for a specific platform:

dotnet publish -c Release -r win-x64

For Linux:

dotnet publish -c Release -r linux-x64

For macOS on Apple Silicon:

dotnet publish -c Release -r osx-arm64

Replace the runtime identifier according to your deployment environment.

One important point: Native AOT requires the appropriate native compiler toolchain. Depending on the operating system, you may need Visual C++ build tools, Clang, or other platform-specific development tools.

Also, publish separately for each operating system and architecture.

Step 4: Reduce Application Size Using Trimming

Trimming removes code that static analysis determines is not required by your application.

For example, a project may reference a library containing dozens of features while using only a small portion of them.

Without trimming, unnecessary code can remain in the published application.

You can enable trimming for a compatible application using:

<PropertyGroup>
    <PublishTrimmed>true</PublishTrimmed>
    <TrimMode>full</TrimMode>
</PropertyGroup>

The full trimming mode allows the linker to remove unused members from assemblies where trimming is supported.

However, trimming requires attention.

Some libraries use reflection to discover classes, methods, or properties dynamically. The linker may not recognize these dependencies through static analysis.

As a result, required code could be removed from the published application.

If your application uses reflection, serialization, dependency injection, or dynamically loaded components, test the trimmed output carefully.

Do not enable full trimming in production without validating the application.

Step 5: Optimize for Size or Execution Speed

Another useful publishing option is OptimizationPreference.

.NET provides this setting to communicate whether the application should prioritize size or execution speed during Native AOT compilation.

For example, to prioritize a smaller executable:

<PropertyGroup>
    <PublishAot>true</PublishAot>
    <OptimizationPreference>Size</OptimizationPreference>
</PropertyGroup>

To prioritize execution speed:

<PropertyGroup>
    <PublishAot>true</PublishAot>
    <OptimizationPreference>Speed</OptimizationPreference>
</PropertyGroup>

The difference is important.

When you choose Size, the compiler favors a smaller native executable. Some execution performance may be affected.

When you choose Speed, the compiler prioritizes execution performance, potentially producing a larger binary.

There is no universal winner. The right choice depends on the workload.

For a short-lived command-line utility, startup and deployment size may matter more than peak throughput.

For a continuously running data-processing application, execution speed may be more important.

Step 6: Compare the Published Output

Do not assume that Native AOT has reduced your application size simply because it is enabled.

Publish the application using different configurations and compare the output.

For example:

dotnet publish -c Release -r win-x64 \
    --self-contained true

For Native AOT:

dotnet publish -c Release -r win-x64 \
    -p:PublishAot=true

For a single-file deployment:

dotnet publish -c Release -r win-x64 \
    -p:PublishSingleFile=true

Record the executable size and total deployment folder size.

You should also measure:

  • Application startup time.
  • Time taken to complete the actual workload.
  • Peak memory consumption.
  • CPU utilization.
  • Build and publishing time.

Remember that an optimized executable is not automatically the fastest application in every scenario.

Native AOT generally improves startup behavior and can reduce memory usage, but a JIT-compiled application may achieve better steady-state throughput for certain workloads.

Step 7: Validate the Application Before Production

This is the part developers should not skip.

A successful Native AOT publish does not guarantee that every application feature will work correctly.

For example, consider an application that dynamically loads assemblies:

var assembly = Assembly.LoadFrom("Plugin.dll");

This type of dynamic loading is not supported in the normal Native AOT deployment model.

Similarly, runtime code generation through Reflection.Emit is not supported.

If your application depends on these capabilities, you may need to redesign that functionality or use a different publishing model.

For JSON serialization, source generation is a useful approach because it makes serialization metadata available at compile time.

For example:

using System.Text.Json;
using System.Text.Json.Serialization;

public class Transaction
{
    public int Id { get; set; }

    public decimal Amount { get; set; }
}

[JsonSerializable(typeof(Transaction))]
internal partial class AppJsonContext
    : JsonSerializerContext
{
}

You can then serialize using the generated metadata:

var transaction = new Transaction
{
    Id = 101,
    Amount = 2500.50m
};

string json = JsonSerializer.Serialize(
    transaction,
    AppJsonContext.Default.Transaction);

Console.WriteLine(json);

This avoids depending on runtime reflection for the serialization metadata.

For production applications, test the actual published executable rather than relying only on tests executed through the development environment.

Common Mistakes to Avoid

MistakeWhy it causes problemsBetter approach
Enabling Native AOT without checking dependenciesSome packages are not AOT-compatibleReview package compatibility
Assuming single-file means smallerBundling can increase executable sizeCompare actual output sizes
Ignoring trimming warningsRequired dynamically accessed members may be removedResolve warnings and test published output
Publishing for the wrong architectureNative binaries are platform-specificUse the correct runtime identifier
Measuring only build timeDoes not represent application performanceMeasure startup and workload execution
Disabling globalization without checking requirementsDate, number, and culture behavior may changeKeep globalization support when needed

Advantages and Disadvantages

Advantages

  • Faster application startup through Native AOT.
  • Potentially lower memory consumption.
  • No separate .NET runtime installation required for Native AOT deployment.
  • Smaller deployment output in many suitable scenarios.
  • Easier distribution of command-line utilities.
  • Reduced dependency on runtime JIT compilation.

Disadvantages

  • Longer publishing and compilation times.
  • Platform-specific builds are required.
  • Dynamic loading and runtime code generation are restricted.
  • Some NuGet dependencies may not support Native AOT.
  • Trimming requires additional testing.
  • The resulting executable may be larger when optimization prioritizes execution speed.

Summary

.NET provides several ways to make console applications smaller and faster, but the best results come from choosing the right publishing strategy for the workload.

Native AOT is particularly useful for short-lived command-line tools, containerized utilities, and applications where startup time and memory consumption matter. Trimming can further reduce unnecessary code, while OptimizationPreference allows developers to prioritize size or execution speed.

However, these optimizations come with compatibility requirements. Applications that depend heavily on reflection, dynamic loading, or runtime code generation may require additional changes.

My recommendation is to start with a normal Release build, measure the application, enable Native AOT, and compare the published results. Keep the optimization only when the measurements demonstrate a real improvement.

The goal is not simply to produce a smaller executable. It is to make the application faster to start, easier to deploy, and more efficient to operate in production.

Windows Hosting Recommendation

HostForLIFE.eu receives Spotlight standing advantage award for providing recommended, cheap and fast ecommerce Hosting including the latest Magento. From the leading technology company, Microsoft. All the servers are equipped with the newest Windows Server 2025, SQL Server 2025, ASP.NET Core 11, ASP.NET MVC 6.0, Silverlight 5, WebMatrix and Visual Studio Lightswitch. Security and performance are at the core of their Magento hosting operations to confirm every website and/or application hosted on their servers is highly secured and performs at optimum level. mutually of the European ASP.NET hosting suppliers, HostForLIFE guarantees 99.9% uptime and fast loading speed. From €3.49/month , HostForLIFE provides you with unlimited disk space, unlimited domains, unlimited bandwidth,etc, for your website hosting needs.
 
https://hostforlifeasp.net/
Read More

Managing Big File Processing Without Preventing ASP.NET Core Requests

Leave a Comment

Business applications sometimes require large file uploads. Users submit documents that require validation before being loaded into a database, Excel sheets with financial data, CSV files with thousands of customer entries, or JSON outputs.


Uploading the file and processing all of its contents in a single ASP.NET Core HTTP request is a frequent error. This method could be effective for little files during development, but when several people upload huge files simultaneously, it might cause major issues.

The better approach is to separate file uploading from file processing. The API should accept the file, store it safely, create a processing job, and return a job ID. A background worker can then process the file without keeping the HTTP request open.

In this article, we will build this approach using ASP.NET Core, background processing, durable storage, and a job status system.

Why Large File Processing Should Not Run Inside an HTTP Request

Consider an application where users upload CSV files containing customer information. After receiving a file, the API reads every row, validates the data, checks for duplicate records, and saves valid records to the database.

If the file contains a few hundred rows, the process may finish quickly. However, a file containing several hundred thousand rows can take much longer.

Processing everything inside the request creates several problems.

Long-running HTTP requests

HTTP requests are not designed to remain open indefinitely. A reverse proxy, load balancer, hosting platform, or client may terminate a request after its configured timeout.

The server might still be processing the file when the connection closes. The user may not know whether the operation completed successfully.

High memory consumption

Loading an entire file into memory creates unnecessary pressure on the application.

For example:

var fileBytes = await file.OpenReadStream()
    .ReadAllBytesAsync();

This approach is unsuitable for large files because the application must hold the file contents in memory.

If several users upload large files simultaneously, memory consumption can increase quickly.

Request resource exhaustion

Long-running operations occupy server resources. Database connections, memory, file handles, and other resources may remain in use while processing continues.

Under heavy traffic, this can affect unrelated API requests.

Duplicate processing

Suppose the server finishes processing a file, but the response never reaches the client. The user may upload the same file again because they believe the first attempt failed.

Without duplicate detection or idempotent processing, the application may import the same records twice.

Use an Asynchronous File Processing Architecture

A more reliable design separates the upload process from the actual processing work.

The API handles the upload and creates a job. A background worker handles the processing.

The workflow looks like this:

Client
  |
  | Upload file
  v
ASP.NET Core API
  |
  | Validate upload
  | Store file
  | Create job record
  | Publish job message
  v
Object Storage + Message Queue
  |
  | Background worker receives job
  v
File Processing Worker
  |
  | Read file in chunks
  | Validate records
  | Save results
  | Update job status
  v
Database

Client --> Job Status API --> Processing Status

Each component has a separate responsibility.

Component

Responsibility

ASP.NET Core API

Accept and validate file uploads

Object storage

Store the uploaded file

Database

Maintain job status and progress

Message queue

Notify workers about pending jobs

Background worker

Process files asynchronously

Status API

Allow clients to check job progress

For cloud applications, use durable object storage such as Azure Blob Storage or Amazon S3 instead of relying on a local application directory. Local storage can become unavailable when an application instance restarts or another instance receives the background job.

Create a File Processing Job Model

Before implementing the upload endpoint, define a model that tracks the processing operation.

public enum FileJobStatus
{
    Pending,
    Processing,
    Completed,
    Failed,
    Cancelled
}

public class FileProcessingJob
{
    public Guid Id { get; set; }

    public string FileName { get; set; } = string.Empty;

    public string StorageKey { get; set; } = string.Empty;

    public FileJobStatus Status { get; set; }

    public int ProcessedRecords { get; set; }

    public int FailedRecords { get; set; }

    public string? ErrorMessage { get; set; }

    public DateTime CreatedAtUtc { get; set; }

    public DateTime? StartedAtUtc { get; set; }

    public DateTime? CompletedAtUtc { get; set; }
}

The job record stores information about the operation, not the actual file contents.

The StorageKey identifies the file in object storage. The processing status helps the API report whether the job is waiting, running, completed, or failed.

For production applications, consider adding tenant information, retry count, a lease expiration time, and a row version for concurrency control.

Upload Files Without Processing Them

The upload endpoint should perform only the work required to accept the file safely.

The following example uses IFormFile and a storage abstraction. The storage implementation is responsible for writing the file to durable object storage.

[ApiController]
[Route("api/files")]
public class FileUploadController : ControllerBase
{
    private readonly IFileStorageService _storage;
    private readonly IFileJobService _jobService;

    public FileUploadController(
        IFileStorageService storage,
        IFileJobService jobService)
    {
        _storage = storage;
        _jobService = jobService;
    }

    [HttpPost("upload")]
    [RequestSizeLimit(100_000_000)]
    public async Task<IActionResult> Upload(
        IFormFile file,
        CancellationToken cancellationToken)
    {
        if (file == null || file.Length == 0)
        {
            return BadRequest("Please select a valid file.");
        }

        if (file.Length > 100_000_000)
        {
            return BadRequest("File size exceeds the allowed limit.");
        }

        var extension = Path.GetExtension(file.FileName);

        if (!string.Equals(
            extension,
            ".csv",
            StringComparison.OrdinalIgnoreCase))
        {
            return BadRequest("Only CSV files are supported.");
        }

        var jobId = Guid.NewGuid();

        var storageKey = $"imports/{jobId:N}.csv";

        await using var fileStream = file.OpenReadStream();

        await _storage.UploadAsync(
            storageKey,
            fileStream,
            cancellationToken);

        var job = new FileProcessingJob
        {
            Id = jobId,
            FileName = Path.GetFileName(file.FileName),
            StorageKey = storageKey,
            Status = FileJobStatus.Pending,
            CreatedAtUtc = DateTime.UtcNow
        };

        await _jobService.CreateJobAsync(
            job,
            cancellationToken);

        await _jobService.EnqueueAsync(
            jobId,
            cancellationToken);

        return AcceptedAtAction(
            nameof(GetJobStatus),
            new { jobId },
            new
            {
                JobId = jobId,
                Status = "Pending",
                Message = "File uploaded and queued for processing."
            });
    }

    [HttpGet("jobs/{jobId:guid}")]
    public async Task<IActionResult> GetJobStatus(
        Guid jobId,
        CancellationToken cancellationToken)
    {
        var job = await _jobService.GetJobAsync(
            jobId,
            cancellationToken);

        if (job == null)
        {
            return NotFound();
        }

        return Ok(job);
    }
}

The important part is that the endpoint does not read or process every CSV record. It uploads the file, creates a job, and returns an HTTP 202 Accepted response.

The client receives a job ID and can use it to check the processing status.

Important considerations for large uploads

This example uses IFormFile for clarity, but it is not automatically a fully streaming upload implementation. ASP.NET Core multipart form handling can buffer uploaded content in memory or temporary files, depending on configuration and file size.

For genuinely large uploads, use a streaming multipart implementation with MultipartReader, or allow clients to upload directly to private object storage using a short-lived, restricted upload URL.

Configure request size limits, multipart limits, proxy limits, and storage limits consistently. Do not rely only on checking file.Length after the request has already been accepted.

Also, never use the original filename as a storage path. Generate a unique storage key and treat the original name as display information only.

Use a Background Worker to Process Files

Once the upload is complete and the job is queued, a background worker can process the file.

For a simple application, ASP.NET Core provides BackgroundService. It is useful for hosted background work, but an in-memory queue alone is not durable. Pending work can be lost when the application restarts.

For production workloads, use a durable message broker such as RabbitMQ or Azure Service Bus. The worker can consume messages from the queue and retrieve the corresponding file from object storage.

A simplified worker might look like this:

public class FileProcessingWorker : BackgroundService
{
    private readonly IFileJobQueue _queue;
    private readonly IFileJobService _jobService;
    private readonly IFileStorageService _storage;
    private readonly IServiceScopeFactory _scopeFactory;

    public FileProcessingWorker(
        IFileJobQueue queue,
        IFileJobService jobService,
        IFileStorageService storage,
        IServiceScopeFactory scopeFactory)
    {
        _queue = queue;
        _jobService = jobService;
        _storage = storage;
        _scopeFactory = scopeFactory;
    }

    protected override async Task ExecuteAsync(
        CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            var jobId = await _queue.DequeueAsync(
                stoppingToken);

            if (jobId == null)
            {
                continue;
            }

            await ProcessJobAsync(
                jobId.Value,
                stoppingToken);
        }
    }

    private async Task ProcessJobAsync(
        Guid jobId,
        CancellationToken cancellationToken)
    {
        var job = await _jobService.GetJobAsync(
            jobId,
            cancellationToken);

        if (job == null)
        {
            return;
        }

        try
        {
            await _jobService.MarkProcessingAsync(
                jobId,
                cancellationToken);

            await using var stream =
                await _storage.OpenReadAsync(
                    job.StorageKey,
                    cancellationToken);

            await using var reader =
                new StreamReader(stream);

            var processed = 0;

            while (await reader.ReadLineAsync(
                cancellationToken) is { } line)
            {
                if (string.IsNullOrWhiteSpace(line))
                {
                    continue;
                }

                await ProcessRecordAsync(
                    line,
                    cancellationToken);

                processed++;

                if (processed % 500 == 0)
                {
                    await _jobService.UpdateProgressAsync(
                        jobId,
                        processed,
                        cancellationToken);
                }
            }

            await _jobService.MarkCompletedAsync(
                jobId,
                processed,
                cancellationToken);
        }
        catch (OperationCanceledException)
            when (cancellationToken.IsCancellationRequested)
        {
            throw;
        }
        catch (Exception ex)
        {
            await _jobService.MarkFailedAsync(
                jobId,
                ex.Message,
                CancellationToken.None);
        }
    }

    private async Task ProcessRecordAsync(
        string record,
        CancellationToken cancellationToken)
    {
        // Parse, validate, and save the record.
        await Task.CompletedTask;
    }
}

This example demonstrates the processing flow. The queue, storage service, and job service are abstractions that need production implementations.

The worker reads the file line by line instead of loading the complete file into memory. It also updates progress periodically rather than writing to the database after every record.

For real CSV processing, use a CSV parser that correctly handles quoted fields, escaped delimiters, and embedded line breaks. Splitting a CSV row using string.Split(',') is not reliable for general CSV data.

Process Records in Batches

Reading a file line by line reduces memory consumption, but saving every record individually can create unnecessary database overhead.

A better approach is to collect a limited number of validated records and save them in batches.

var batch = new List<CustomerImportRecord>();

while (await reader.ReadLineAsync(
    cancellationToken) is { } line)
{
    var record = ParseCustomerRecord(line);

    if (record == null)
    {
        continue;
    }

    batch.Add(record);

    if (batch.Count >= 500)
    {
        await repository.SaveBatchAsync(
            batch,
            cancellationToken);

        batch.Clear();
    }
}

if (batch.Count > 0)
{
    await repository.SaveBatchAsync(
        batch,
        cancellationToken);
}

The batch size should be based on database performance, record size, transaction limits, and available memory.

A batch size of 500 is only an example. Measure the application under realistic workloads before choosing a production value.

For applications where partial imports are allowed, record invalid rows separately and continue processing valid records. If the import must be all-or-nothing, use a staging table and a controlled final transaction or promotion step.

Make Job Creation Reliable

There is an important problem in the upload example.

Suppose the application saves the job record successfully but fails before publishing the queue message. The database contains a pending job, but no worker receives it.

The opposite situation can also happen if a message is published before the job transaction is committed.

The transactional outbox pattern helps solve this problem.

In a single database transaction, save both the job record and an outbox message. A separate publisher reads unpublished outbox records and sends them to the message broker. After successful publication, it marks the outbox message as published.

This makes job creation and message publication recoverable without requiring a distributed transaction.

Workers must also be idempotent. Message brokers can deliver messages more than once, especially when a worker crashes after completing work but before acknowledging the message.

Before processing, the worker should acquire the job using an atomic state transition or lease. A completed job should not be processed again simply because an old message was delivered.

For database imports, use a stable business key or an import-specific idempotency key to prevent duplicate records.

Track Processing Progress

Users should not have to guess whether their uploaded file is still being processed.

A status endpoint can return information such as:

{
  "jobId": "9d0c4d7e-0e2a-4c4a-bc4f-0d2e8c1f9a31",
  "status": "Processing",
  "processedRecords": 12500,
  "failedRecords": 18,
  "createdAtUtc": "2026-11-02T08:30:00Z",
  "startedAtUtc": "2026-11-02T08:30:04Z"
}

The frontend can periodically call the status endpoint to display progress.

For applications that need immediate updates, SignalR can notify connected clients when the job status changes.

Do not update progress for every row. Frequent database writes can become a performance problem. Update after a fixed number of records or after a reasonable time interval.

If the total number of records is unknown, show the number processed rather than displaying an inaccurate percentage.

Handle Failures and Retries

Background processing does not mean failures disappear. Storage services, databases, message brokers, and file parsers can all fail.

A production implementation should consider the following cases:

Failure

Recommended handling

Temporary database outage

Retry with exponential backoff

Object storage unavailable

Retry the storage operation

Invalid file structure

Mark the job as failed

Invalid individual record

Record the error and continue if partial imports are allowed

Worker restart

Allow the durable queue to redeliver unacknowledged messages

Repeated processing failure

Move the message to a dead-letter queue

Duplicate queue message

Use job state checks and idempotent operations

Do not retry every exception indefinitely. A malformed file will not become valid after another attempt.

Separate transient errors from permanent errors. Configure a maximum retry count and preserve enough diagnostic information to investigate failures.

Avoid exposing internal exception messages, database details, or storage paths through the public status API. Store detailed diagnostics in protected logs and return a safe error message to the client.

Security Considerations for File Processing

File uploads create a security boundary. A file extension alone does not prove that a file contains valid data.

Apply these controls:

  1. Validate file size, extension, expected format, and actual content.

  2. Generate storage keys instead of trusting user-provided filenames.

  3. Store uploaded files in private storage.

  4. Verify that the requesting user owns the job before returning its status.

  5. Scan files for malware when the application handles untrusted uploads.

  6. Restrict archive extraction size and file count to protect against archive bombs.

  7. Apply parser limits to avoid excessively large fields, deeply nested JSON, or malformed documents.

  8. Delete temporary files and expired uploads according to a defined retention policy.

  9. Avoid logging sensitive file contents or personal information.

If the application processes files for multiple customers, include tenant ownership in job queries and storage access checks. A user should never be able to retrieve another tenant's file by changing a job ID.

Common Mistakes to Avoid

Loading the complete file into memory

Avoid ReadAllBytes, File.ReadAllText, or copying an entire large file into a MemoryStream when streaming is possible.

Using an in-memory queue for critical jobs

An in-memory queue is convenient for demonstrations, but pending messages may disappear when the application restarts. Use durable messaging for important processing tasks.

Running too many jobs simultaneously

Unrestricted concurrency can overload the database, storage service, or application instance. Configure worker concurrency based on available resources and downstream service capacity.

Treating every failure as retryable

Invalid file formats and business validation failures should usually be handled as permanent failures. Retrying them wastes resources.

Keeping uploaded files forever

Define a retention policy. Delete files after successful processing when they are no longer needed, or retain them for a documented audit period.

Ignoring job ownership

Every status, cancellation, and download endpoint should verify the caller's authorization to access the job.

How to Test Large File Processing

Testing with a small sample file is not enough. Test the complete workflow under realistic conditions.

Include these scenarios:

  • Upload a file close to the configured size limit.

  • Upload multiple files concurrently.

  • Include malformed records and unexpected data types.

  • Disconnect the client during an upload.

  • Restart a worker while a job is running.

  • Deliver the same queue message more than once.

  • Simulate temporary database and object storage failures.

  • Verify that a failed job can be investigated and safely retried.

  • Measure memory usage while processing files of different sizes.

Monitor upload duration, queue waiting time, processing duration, records processed per second, failure rates, worker concurrency, memory consumption, and temporary storage usage.

These measurements help identify whether the bottleneck is file reading, validation, database writes, or downstream services.

Summary

Large file processing should not depend on an HTTP request remaining open until every record has been processed.

A better ASP.NET Core design accepts the upload, stores the file in durable object storage, creates a processing job, and returns HTTP 202 Accepted with a job ID. A background worker then reads the file in manageable chunks, validates the data, saves records in batches, and updates the job status.

For production applications, combine durable messaging, transactional outbox publishing, idempotent processing, controlled concurrency, retry policies, and proper file security.

This design keeps API requests responsive, limits memory consumption, and makes long-running file imports easier to monitor, recover, and scale.

Windows Hosting Recommendation

HostForLIFE.eu receives Spotlight standing advantage award for providing recommended, cheap and fast ecommerce Hosting including the latest Magento. From the leading technology company, Microsoft. All the servers are equipped with the newest Windows Server 2025, SQL Server 2025, ASP.NET Core 11, ASP.NET MVC 6.0, Silverlight 5, WebMatrix and Visual Studio Lightswitch. Security and performance are at the core of their Magento hosting operations to confirm every website and/or application hosted on their servers is highly secured and performs at optimum level. mutually of the European ASP.NET hosting suppliers, HostForLIFE guarantees 99.9% uptime and fast loading speed. From €3.49/month , HostForLIFE provides you with unlimited disk space, unlimited domains, unlimited bandwidth,etc, for your website hosting needs.
 
https://hostforlifeasp.net/
Read More

How to Identify Critical Changes Prior to Release using ASP.NET Core API Tests?

Leave a Comment

Even if an API passes every test in its own project, it might still cause problems for the apps that rely on it. An endpoint may begin delivering a new status code, a property name may change, or a response field may become nullable. During development, these modifications can seem insignificant, but they can lead to problems with frontend, mobile, and third-party integrations.


Because of this, evaluating an API entails more than just seeing if its endpoints provide the desired information.

You also need to verify that the API continues to follow the contract consumers rely on.

In ASP.NET Core, you can combine integration tests, response validation, OpenAPI document checks, and contract testing to catch breaking changes before release. This article explains how to build that testing approach using practical C# examples.

What Is an API Breaking Change?

An API breaking change occurs when an existing consumer can no longer use an API in the way it previously could.

For example, imagine an endpoint returns this JSON response:

{
  "id": 101,
  "name": "Laptop",
  "price": 799.99
}

A frontend application expects the name property to display the product title.

Now suppose a developer renames the property to productName:

{
  "id": 101,
  "productName": "Laptop",
  "price": 799.99
}

The API might still return HTTP 200, and its internal tests might pass. However, a consumer expecting name may stop displaying the product correctly.

Breaking changes can affect several parts of an API contract:

  • Routes, HTTP methods, and query parameters.
  • Request and response property names.
  • Data types and nullability.
  • HTTP status codes.
  • Authentication and authorization requirements.
  • Validation rules and error response formats.
  • Pagination behavior and default values.

A good API testing strategy checks these behaviors, not just whether the application starts successfully.

Create an ASP.NET Core API Test Project

For this example, assume an ASP.NET Core application exposes a product endpoint.

A typical solution structure might look like this:

ProductApi/
    Controllers/
    Models/
    Program.cs

ProductApi.Tests/
    ProductApi.Tests.csproj
    ProductEndpointTests.cs

The test project should reference the API project and include a compatible version of Microsoft.AspNetCore.Mvc.Testing, along with a test framework such as xUnit.

The ASP.NET Core integration testing infrastructure provides WebApplicationFactory<TEntryPoint>, which allows tests to start the application in a test host and send HTTP requests without deploying it to a real server.

For applications that use top-level statements, you may need to expose the entry point to the test project. One common approach is to add the following declaration at the end of Program.cs:

public partial class Program
{
}

This makes the generated Program type accessible to the test project when configured appropriately.

Write an Integration Test for an API Endpoint

Integration tests verify how the API behaves when the application processes an actual HTTP request. Unlike isolated unit tests, they can exercise routing, middleware, model binding, serialization, filters, and endpoint logic together.

Consider this response model:

public sealed record ProductResponse(
    int Id,
    string Name,
    decimal Price);

The API exposes a route such as GET /api/products/101.

A basic integration test can verify the status code and response data.

using System.Net;
using System.Net.Http.Json;
using Microsoft.AspNetCore.Mvc.Testing;
using Xunit;

public sealed class ProductEndpointTests
    : IClassFixture<WebApplicationFactory<Program>>
{
    private readonly HttpClient _client;

    public ProductEndpointTests(
        WebApplicationFactory<Program> factory)
    {
        _client = factory.CreateClient();
    }

    [Fact]
    public async Task GetProduct_ReturnsExpectedResponse()
    {
        var response = await _client.GetAsync(
            "/api/products/101");

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

        var product =
            await response.Content
                .ReadFromJsonAsync<ProductResponse>();

        Assert.NotNull(product);
        Assert.Equal(101, product.Id);
        Assert.Equal("Laptop", product.Name);
        Assert.Equal(799.99m, product.Price);
    }
}

This test assumes that the test environment provides a product with ID 101 and that the API returns the stated values. In a real project, arrange the required test data or replace the production data source with a test implementation.

The test verifies more than whether the endpoint returns HTTP 200. It also checks whether the response contains the expected values and can be deserialized into the expected model.

However, deserialization alone is not always enough. Depending on serializer settings and model definitions, an unexpected JSON property may be ignored, or a missing property may receive a default value. You should also test the response contract directly when the exact JSON shape matters.

Verify the JSON Response Contract

Suppose a consumer requires the name property to remain part of the response. You can inspect the raw JSON to catch accidental changes.

using System.Net;
using System.Text.Json;
using Xunit;

[Fact]
public async Task GetProduct_PreservesRequiredJsonProperties()
{
    var response = await _client.GetAsync(
        "/api/products/101");

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

    using var document = JsonDocument.Parse(
        await response.Content.ReadAsStringAsync());

    var root = document.RootElement;

    Assert.True(
        root.TryGetProperty("id", out var id));

    Assert.True(
        root.TryGetProperty("name", out var name));

    Assert.True(
        root.TryGetProperty("price", out var price));

    Assert.Equal(101, id.GetInt32());
    Assert.Equal("Laptop", name.GetString());
    Assert.Equal(799.99m, price.GetDecimal());
}

This test fails if the name property is renamed or removed. It also verifies the values and expected JSON types.

The JSON property names used by the test must match the API's actual serialization contract. ASP.NET Core applications commonly use camel-case JSON names, but serializer configuration can change that behavior.

When Should You Compare the Entire JSON Response?

Checking individual properties is useful when consumers depend on a small, stable set of fields.

For APIs with strict response contracts, you may also compare the complete JSON structure against an approved fixture or snapshot. This can detect changes to nested objects, property names, and response shapes.

Full-response comparisons need careful maintenance. A harmless addition may fail a strict comparison even when existing consumers remain compatible. Decide whether additional fields are allowed before choosing the test approach.

Test HTTP Status Codes and Error Responses

An endpoint's contract includes its failure behavior. Consumers may depend on receiving 404 Not Found for a missing resource or 400 Bad Request for invalid input.

For example:

[Fact]
public async Task GetUnknownProduct_ReturnsNotFound()
{
    var response = await _client.GetAsync(
        "/api/products/999999");

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

This test assumes the API returns 404 when the requested product does not exist.

You should also test invalid request data. For an endpoint that creates a product, useful scenarios include a missing required name, a negative price, malformed JSON, and an unauthenticated request.

The expected status code depends on the API's documented behavior. For example, an API might use 400 for validation errors and 401 when authentication is missing. Tests should reflect the actual contract rather than impose arbitrary expectations.

For applications that return structured validation errors, verify important fields in the error response as well. Otherwise, a change to the error format may break frontend validation messages even when the status code remains unchanged.

Detect Changes in the OpenAPI Document

Integration tests cover specific scenarios. An OpenAPI document provides a broader description of an API's public contract, including paths, methods, parameters, request bodies, response schemas, and security requirements.

Checking the OpenAPI document can help detect changes that individual endpoint tests do not cover.

For example, suppose an API previously exposed this operation:

paths:
  /api/products/{id}:
    get:
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: integer

A later change might remove the endpoint, rename its route, or change the parameter type. A contract comparison can identify these differences before release.

Use OpenAPI Contract Checks

A practical approach is to generate the OpenAPI document during the build or from a controlled test environment, then compare it with the version approved for the current API release.

The comparison should identify changes such as:

  • Removed paths or HTTP methods.
  • Removed request or response properties.
  • Changed property types.
  • New required request fields.
  • Changes to authentication requirements.
  • Removed response status codes.

Not every difference is necessarily breaking. Adding an optional response property is often compatible with existing clients, while removing a required field may not be. The comparison tool and review process should account for the rules your API follows.

Also, OpenAPI checks cannot replace runtime tests. A document may describe the correct response schema even when the endpoint returns different data due to a serialization or business-logic problem.

Add Consumer-Driven Contract Testing

Integration tests usually focus on the API provider's expected behavior. Consumer-driven contract testing adds another perspective: it verifies the interactions that actual consumers rely on.

Imagine a product API used by a web application and a mobile application. The web application may depend on the product name and price, while the mobile application may also depend on an image URL.

A consumer-driven contract records the expected request and response for a specific interaction. The provider can then verify that its implementation still satisfies those expectations.

This approach is especially useful when multiple teams maintain separate services and deploy them independently.

Testing approachMain purposeBest use
Unit testsVerify isolated application logicBusiness rules and validation
Integration testsVerify real application request handlingRouting, middleware, serialization, and status codes
JSON contract testsVerify response fields and valuesStable API response shapes
OpenAPI comparisonIdentify changes to the documented APIRelease reviews and compatibility checks
Consumer-driven contract testsVerify interactions required by consumersMicroservices and independently deployed applications

Contract testing does require coordination. Teams need to maintain consumer expectations and decide when a contract change is intentional. Without that process, contract tests can become outdated and block legitimate improvements.

Run API Tests in CI/CD Before Release

Automated tests provide the most value when they run before changes reach production.

Add API tests to your continuous integration pipeline so that a pull request or release candidate cannot proceed when required contract checks fail.

A typical pipeline might follow this sequence:

  1. Restore dependencies and compile the solution.
  2. Run unit tests.
  3. Run integration tests against the test configuration.
  4. Generate or validate the OpenAPI document.
  5. Compare the API contract with the approved baseline.
  6. Publish test results and block the release when required checks fail.

For example, a pipeline can execute the test project with the .NET CLI:

dotnet restore
dotnet build --no-restore
dotnet test --no-build

These commands assume the solution has already been configured to include the relevant test project. The OpenAPI comparison and contract-testing steps must be added separately using the tools selected by your team.

Keep test configuration isolated from production. Use test databases, controlled test data, and test credentials. Avoid making destructive requests against production services as part of automated compatibility checks.

Common Mistakes to Avoid

Testing Only the HTTP Status Code

A successful status code does not guarantee that the response contains the expected properties or values. Validate the response body whenever consumers depend on its structure.

Sharing Production Data with Tests

Tests that depend on changing production records can become unreliable. Create predictable test data or use a controlled test data source.

Ignoring Error Responses

Clients often rely on validation errors, authentication failures, and missing-resource responses. Test these cases alongside successful requests.

Treating Every OpenAPI Difference as Breaking

A new optional property may be compatible with existing clients. Review schema changes based on consumer expectations instead of blocking every difference automatically.

Running Contract Tests Only Before Deployment

Finding a breaking change during a release is more expensive than detecting it during a pull request. Run the essential checks early and repeat them at release time when appropriate.

Best Practices for Reliable API Testing

A reliable strategy combines several testing levels instead of relying on one tool.

  • Define the contract: Document important routes, status codes, request fields, response fields, and authentication requirements.
  • Test consumer-critical behavior: Focus on the fields and interactions that existing applications actually use.
  • Keep tests deterministic: Control test data, environment variables, and external dependencies.
  • Validate error behavior: Treat failure responses as part of the API contract.
  • Review schema changes: Use OpenAPI comparison to identify changes that deserve compatibility review.
  • Test backward compatibility: When supporting existing clients, verify that new versions preserve the interactions those clients require.
  • Make failures actionable: Include the endpoint, expected behavior, and actual result in test failure messages.

Advantages and Limitations

AdvantagesLimitations
Detects incompatible changes before releaseRequires maintenance of tests and contract baselines
Protects frontend and mobile consumersCannot automatically represent every consumer's behavior
Improves confidence in API versioningIntegration tests may need database and service setup
Makes release reviews more consistentStrict snapshots can flag harmless changes
Helps multiple teams coordinate API changesConsumer-driven contracts require team coordination

The right balance depends on the application. A small internal API may need integration tests and a few contract checks. A public API with many independent consumers may benefit from a formal compatibility policy, OpenAPI diffing, and consumer-driven contract testing.

Summary

Breaking API changes often involve small differences that are easy to miss during development. A renamed JSON property, a changed status code, or a new required request field can disrupt applications even when the API still builds and starts correctly.

ASP.NET Core integration tests help verify real HTTP behavior. JSON contract tests protect important response fields, while OpenAPI comparison identifies changes to the documented interface. Consumer-driven contract tests add another layer of protection when multiple applications depend on the same API.

Run these checks in CI/CD, use predictable test data, and review compatibility changes before release. This approach helps teams identify API problems earlier and release changes with greater confidence.

https://hostforlifeasp.net/ 

Read More
Previous PostOlder Posts Home