European ASP.NET 4.5 Hosting BLOG

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

European ASP.NET Core 10.0 Hosting - HostForLIFE :: Making Use of ASP.NET Core Logs in the Event of Multiple Service Request Failures

clock November 23, 2026 11:47 by author Peter

Examining a failed request is very simple when an ASP.NET Core application operates as a single service. To determine what went wrong, a developer can go through the application logs, find the exception, and follow the execution route. When an application depends on several services, the problem gets more difficult. An API gateway, an ASP.NET Core application, a database, an external payment provider, and a background processing system might all be reached by a single request. Any of these elements might be the source of the problem if the final procedure fails.

Consider an e-commerce application where a customer places an order. The API receives the request, validates the customer, checks inventory, calculates the total amount, processes payment, and saves the order. Suppose the payment service responds successfully, but the database operation fails while saving the order. The customer receives an error, but the application may already have completed part of the operation.

Looking at the final exception alone does not explain the complete sequence of events. Developers need to understand which services were called, how long each operation took, which component returned an error, and whether an earlier operation had already completed.

This is where structured logging and distributed tracing become important.

ASP.NET Core provides a built-in logging abstraction through ILogger<T>, while .NET also supports distributed tracing through Activity and the OpenTelemetry ecosystem. When these capabilities are configured correctly, logs become more than a collection of error messages. They become useful diagnostic records that help developers reconstruct what happened across application boundaries.

Why Traditional Application Logs Are Not Enough?

Many applications begin with simple logging statements:
_logger.LogInformation("Order request received");

_logger.LogError("Unable to process order");

These messages are useful during development, but they provide very little information when investigating production failures.

Imagine that three customers report that order creation is failing. The application logs contain hundreds of messages saying that an order request was received, but none of them clearly identifies which messages belong to the same request.

Developers may try to correlate events using timestamps, usernames, or request URLs. This approach becomes unreliable when multiple requests are processed simultaneously. Two customers can place orders within milliseconds of each other, and several services may write logs independently.

There are three major problems with this style of logging.

First, the messages do not contain enough context. A message such as Payment failed does not tell the developer which payment provider was contacted, which operation failed, or whether the failure was caused by a timeout, an authentication problem, or a business validation rule.

Second, the logs do not share a consistent identifier. Without a correlation mechanism, connecting events from the API, payment service, and database becomes difficult.

Third, logging often focuses only on failures. Successful operations are also important because they establish what happened before the failure. If payment processing completed successfully but order persistence failed, that distinction matters when diagnosing the incident.

A useful logging strategy should capture the important stages of a request while keeping sensitive information out of the logs.

Use ILogger With Structured Logging
ASP.NET Core applications commonly use ILogger<T> for application logging. The interface provides different log levels and allows developers to include structured properties with each message.

Consider an order service that processes a request:
public class OrderService
{
    private readonly ILogger<OrderService> _logger;

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

    public async Task ProcessOrderAsync(
        int orderId,
        CancellationToken cancellationToken)
    {
        _logger.LogInformation(
            "Starting order processing for {OrderId}",
            orderId);

        try
        {
            await SaveOrderAsync(
                orderId,
                cancellationToken);

            _logger.LogInformation(
                "Order processing completed for {OrderId}",
                orderId);
        }
        catch (Exception ex)
        {
            _logger.LogError(
                ex,
                "Order processing failed for {OrderId}",
                orderId);

            throw;
        }
    }

    private Task SaveOrderAsync(
        int orderId,
        CancellationToken cancellationToken)
    {
        // Database operation
        return Task.CompletedTask;
    }
}


The important difference is the use of named properties such as {OrderId} instead of constructing the entire message through string interpolation.

Structured logging preserves the order ID as a separate property. A logging provider can store it as a searchable field, allowing developers to filter events by order ID without searching through the complete message text.

For example, a log entry might contain:

{
  "level": "Information",
  "message": "Starting order processing for 10542",
  "OrderId": 10542,
  "category": "OrderService"
}


The actual JSON structure depends on the logging provider and its configuration, but the principle remains the same: important diagnostic values should be recorded as structured properties.

This becomes especially useful when a logging platform supports filtering, aggregation, and dashboards. Developers can search for a specific order, compare processing durations, and identify repeated failures without manually reading every log entry.

Understand the Different Log Levels
Not every event deserves the same level of attention. ASP.NET Core provides standard logging levels that help teams distinguish normal application activity from unexpected behavior.

Log level

When to use it

Example

Trace

Very detailed diagnostic information

Internal processing details

Debug

Information useful during development and investigation

Selected configuration decisions

Information

Normal application operations

Order successfully created

Warning

Unexpected situations that do not necessarily stop processing

External service retry

Error

An operation failed

Database save failed

Critical

A failure affecting the application or an essential service

Application cannot connect to its required database

A common mistake is logging every exception as an error. Some exceptions are part of normal application behavior. For example, a client disconnecting during a request does not always indicate an application defect.

Similarly, a temporary external service failure may be logged as a warning when the application successfully retries the operation.

Choosing the correct log level improves monitoring quality. If every event is recorded as an error, important failures become harder to distinguish from expected operational conditions.

Correlate Logs Across Multiple Services

The next challenge is connecting logs generated by different services.

ASP.NET Core supports request-level correlation through Activity and diagnostic context. When distributed tracing is enabled, an incoming request can have a trace identifier that is propagated to downstream operations.

For example, an order request might follow this sequence:
Client Request
      |
      v
Order API
      |
      +------ Inventory Service
      |
      +------ Payment Service
      |
      +------ Database
      |
      v
Order Response

Each service can generate its own logs, but all operations should be associated with the same distributed trace.

A trace ID identifies the overall operation, while a span ID identifies an individual operation within that trace.

For example:
{
  "service": "order-api",
  "traceId": "4bf92f3577b34da6a3ce929d0e0e4736",
  "spanId": "00f067aa0ba902b7",
  "message": "Starting order processing"
}

The payment service may produce another record with the same trace ID but a different span ID.

This allows a tracing platform to reconstruct the request path and show how much time was spent in each service.

.NET uses the Activity API to represent these operations. ASP.NET Core automatically creates activities for incoming HTTP requests when diagnostic instrumentation is enabled. Supported HTTP client instrumentation can create activities for outgoing requests as well.

For a custom operation, developers can create an activity explicitly:
using System.Diagnostics;

public class OrderService
{
    private static readonly ActivitySource ActivitySource =
        new("OrderService");

    private readonly ILogger<OrderService> _logger;

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

    public async Task ProcessOrderAsync(
        int orderId,
        CancellationToken cancellationToken)
    {
        using var activity = ActivitySource.StartActivity(
            "ProcessOrder");

        activity?.SetTag("order.id", orderId);

        _logger.LogInformation(
            "Processing order {OrderId}",
            orderId);

        await Task.Delay(100, cancellationToken);
    }
}

The ActivitySource represents the component producing tracing information. The activity records the operation and can include useful attributes such as the order ID.

The activity is disposed when processing finishes, which ends the operation and allows the tracing infrastructure to record its duration.

However, creating an ActivitySource does not automatically export traces to a monitoring platform. The application needs a configured listener or tracing provider, such as OpenTelemetry, to collect and export the activity data.

Add OpenTelemetry for Distributed Observability

For applications that communicate with multiple services, OpenTelemetry provides a standard approach to collecting traces, metrics, and logs.

The .NET OpenTelemetry ecosystem supports instrumentation for ASP.NET Core, HTTP clients, and other application components. Developers can combine automatic instrumentation with custom activities to understand both framework-level operations and application-specific business workflows.

A typical ASP.NET Core application can configure tracing in Program.cs:
using OpenTelemetry.Resources;
using OpenTelemetry.Trace;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddOpenTelemetry()
    .ConfigureResource(resource =>
        resource.AddService("OrderApi"))
    .WithTracing(tracing =>
    {
        tracing
            .AddAspNetCoreInstrumentation()
            .AddHttpClientInstrumentation()
            .AddSource("OrderService");
    });

builder.Services.AddControllers();

var app = builder.Build();

app.MapControllers();

app.Run();


This configuration registers tracing for incoming ASP.NET Core requests, outgoing HTTP client calls, and custom activities created through the OrderService activity source.

An exporter must also be configured to send the collected telemetry to an observability backend. The appropriate exporter depends on the monitoring platform used by the organization.

For example, an OpenTelemetry Protocol exporter can send traces to a collector, which can then forward the data to a compatible tracing backend.

The advantage of this approach is that application code does not need to manually create correlation identifiers for every downstream request. Supported instrumentation handles propagation automatically when the required context is available.

For services that communicate through message queues, developers may need additional instrumentation to propagate trace context through message headers. HTTP propagation alone does not cover every asynchronous communication pattern.

Propagate Correlation Context to Downstream Services

A distributed trace is useful only when its context can move between services.

For HTTP communication, the W3C Trace Context standard defines headers such as traceparent and tracestate. These headers allow supported services to continue an existing trace rather than starting an unrelated one.

A typical traceparent header looks like this:
traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01

It contains the trace ID, parent span ID, and trace flags.

When an ASP.NET Core application receives a request containing valid trace context, the tracing infrastructure can continue the existing trace. When the application calls another instrumented service, the context can be propagated through the outgoing request.

For example, an order API might call a payment service using HttpClient:
public class PaymentClient
{
    private readonly HttpClient _httpClient;

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

    public async Task ProcessPaymentAsync(
        CancellationToken cancellationToken)
    {
        using var response = await _httpClient.PostAsync(
            "/payments",
            content: null,
            cancellationToken);

        response.EnsureSuccessStatusCode();
    }
}


When HTTP client tracing and standard context propagation are configured, the outgoing request can carry the trace context automatically. Avoid manually generating a new trace ID for every downstream call. Doing so breaks the relationship between the parent request and its child operations. Also, do not blindly trust externally supplied correlation headers for security decisions. Trace context is useful for observability, but it is not an authentication mechanism.

Capture Exceptions With Enough Diagnostic Context

When a request fails, the exception itself is only part of the information needed to investigate the problem.

Developers should also record the operation being performed, relevant business identifiers, the affected dependency, and the outcome of the operation.

Consider a payment operation:
public async Task ProcessPaymentAsync(
    int orderId,
    CancellationToken cancellationToken)
{
    try
    {
        await _paymentClient.ProcessAsync(
            orderId,
            cancellationToken);

        _logger.LogInformation(
            "Payment completed for order {OrderId}",
            orderId);
    }
    catch (HttpRequestException ex)
    {
        _logger.LogError(
            ex,
            "Payment service communication failed for order {OrderId}",
            orderId);

        throw;
    }
}


This log provides more useful information than a generic message such as Payment failed. It identifies the operation and the business entity involved while preserving the exception details for diagnostics.

However, avoid logging complete payment requests, authorization headers, customer passwords, access tokens, or card information. Structured logging does not make sensitive information safe merely because it is stored in separate fields.

A good production logging policy should define which business identifiers can be recorded and which values must be masked or excluded.

Make Logs Useful Without Creating Too Much Noise

Adding more logging does not automatically improve observability. Excessive logging can increase storage costs, make dashboards difficult to interpret, and introduce performance overhead.

For example, logging every item in a large order can generate thousands of records for a single request. In most cases, a single structured event containing the order ID, item count, processing duration, and result is more useful.

Use logs for discrete events and important decisions. Use traces to understand the path and duration of an operation. Use metrics to monitor trends such as request rates, failure percentages, and latency distributions.

These three signals complement one another.

A metric might reveal that payment requests are experiencing increased latency. A distributed trace can show that the payment service is responsible for most of the delay. Logs can then provide the detailed error message or business context needed to understand why the operation failed.

This is a more effective diagnostic process than relying on a large collection of unstructured log statements.

Common Mistakes in ASP.NET Core Logging
One common mistake is using string interpolation for every log message:
_logger.LogInformation(
    $"Order {orderId} processed successfully");


Although this produces readable output, it constructs the message before passing it to the logging provider. Structured templates are preferable because they preserve named properties and allow providers to filter and aggregate events more effectively.

Another mistake is generating a new correlation ID inside every service. This disconnects related operations and makes distributed tracing less useful. Use the existing trace context and allow supported instrumentation to propagate it.

Teams also sometimes log exceptions without including the exception object:
_logger.LogError(
    "Database operation failed");


This loses important diagnostic information such as the exception type and stack trace. When appropriate, pass the exception as the first argument to the logging method.

Finally, avoid treating logs as a replacement for metrics and tracing. Logs explain individual events, but they are not the most efficient way to understand the overall performance of a distributed application.

Best Practices for Production Applications

A production logging strategy should start with consistent structured logging across services. Use meaningful property names, standard log levels, and a shared approach to identifying requests and business operations.

Enable distributed tracing for incoming requests and outgoing HTTP calls. Use custom activities for important operations that are not covered by automatic instrumentation. Ensure that trace context is propagated through message queues and background processing where appropriate.

Define a clear policy for sensitive information. Avoid recording passwords, access tokens, authorization headers, payment details, and other confidential values. Apply the same rules to exception messages and diagnostic context.

Also, establish retention policies and access controls for centralized logs. Production logs can contain operational and business information, so they should not be accessible to everyone by default.

Finally, test the logging behavior when dependencies fail. Simulate database timeouts, unavailable external APIs, request cancellations, and failed message processing. Verify that the resulting logs contain enough context to identify the problem without exposing sensitive information.

Summary
When an ASP.NET Core request passes through multiple services, a single error message rarely explains the complete failure. Developers need structured logs, consistent correlation, and distributed tracing to understand how a request moved through the system and where it failed. ILogger<T> provides structured application logging, while .NET Activity and OpenTelemetry help connect operations across service boundaries. Together, they make it possible to investigate failures using request context, trace IDs, span information, execution durations, and meaningful application events.

The goal is not to log every operation or produce as much diagnostic information as possible. It is to capture the information that helps developers answer three important questions: What happened, where did it happen, and why did it fail? When logging and tracing are designed around these questions, troubleshooting becomes faster, production incidents become easier to investigate, and development teams gain a much clearer understanding of application behavior.

HostForLIFE.eu ASP.NET Core 11.0 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



European ASP.NET Core 10.0 Hosting - HostForLIFE :: Waiting for GitHub Pull Request Events Without Polling

clock November 20, 2026 12:02 by author Peter

GitHub-integrated applications frequently have to respond when a pull request is affected. When a pull request is opened, for instance, an internal development platform may need to initiate a validation step. New review comments may need to be processed by a code review assistant. When a pull request is merged, a deployment system may have to react.

Asking GitHub if anything has changed is the simple method.

Polling is what that is.

Application
    |
    | "Has the PR changed?"
    v
GitHub API
    |
    | No
    v
Wait
    |
    | "Has the PR changed?"
    v
GitHub API


This approach is simple, but it creates unnecessary API requests, adds delay, and becomes harder to manage as the number of repositories and pull requests increases.

A better approach is event-driven integration.

Instead of repeatedly asking GitHub for changes, configure GitHub to notify your application when the required event occurs. Your application can then process the event and perform the appropriate action.

Pull Request Event
        |
        v
GitHub Webhook
        |
        v
Your API
        |
        v
Validate / Queue / Process

This article explains how to build that pattern with ASP.NET Core and GitHub webhooks while focusing on reliable production behavior.

Polling vs Event-Driven Processing

Polling means that your application periodically checks GitHub for changes.

For example:
while (!cancellationToken.IsCancellationRequested)
{
    await CheckPullRequestsAsync(cancellationToken);

    await Task.Delay(
        TimeSpan.FromSeconds(30),
        cancellationToken);
}


This works, but the application cannot know exactly when a change happens. If the interval is 30 seconds, a new pull request may be detected almost immediately or nearly 30 seconds later. Polling also creates requests when nothing has changed. Webhooks reverse the responsibility.

GitHub sends an HTTP request to your application when an event occurs.

Area

Polling

Webhooks

Detection

Application asks GitHub

GitHub sends event

API requests

Repeated

Event-driven

Reaction time

Depends on interval

Usually near event time

Idle traffic

High

Low

Implementation

Simple initially

Requires endpoint and security

Reliability

Requires tracking state

Requires delivery handling

Scaling

Can become expensive

Better suited to event-driven workloads

For event-driven applications, webhooks are generally a better fit when the external platform already provides reliable event notifications.

What Is a GitHub Pull Request Webhook?
A GitHub webhook allows an application to receive HTTP notifications when selected repository events occur.

For pull request processing, the webhook can be configured for events such as:
opened
closed
reopened
synchronize
edited
labeled
unlabeled


The exact events you need depend on the application.
For example, if a code validation service needs to run whenever new commits are pushed to an existing pull request, the synchronize event is important.
If the application only needs to know when a pull request is created, opened may be sufficient.
This distinction matters because subscribing to unnecessary events increases processing work.

Designing the ASP.NET Core Webhook Endpoint

A webhook receiver should be small and focused.

A minimal ASP.NET Core endpoint can look like this:
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/github/webhooks")]
public class GitHubWebhookController : ControllerBase
{
    [HttpPost]
    public IActionResult Receive()
    {
        var eventName = Request.Headers["X-GitHub-Event"].ToString();

        return Ok(new
        {
            Event = eventName
        });
    }
}

The X-GitHub-Event header tells the application which GitHub event was delivered.
However, production webhook handling requires more than reading the event name.

The application should validate the request, identify the repository and event, process only supported events, and avoid doing long-running work directly inside the HTTP request.

Validate the Webhook Signature

A webhook endpoint is publicly reachable in most architectures.
That means anyone who knows the endpoint could potentially send a fake request.

GitHub supports webhook signatures that allow the receiving application to verify that a request was generated using the configured webhook secret.

A typical ASP.NET Core implementation can calculate the HMAC SHA-256 signature:
using System.Security.Cryptography;
using System.Text;

static bool IsValidSignature(
    string payload,
    string signature,
    string secret)
{
    var key = Encoding.UTF8.GetBytes(secret);
    var body = Encoding.UTF8.GetBytes(payload);

    using var hmac = new HMACSHA256(key);

    var hash = hmac.ComputeHash(body);

    var expected =
        "sha256=" + Convert.ToHexString(hash).ToLowerInvariant();

    return CryptographicOperations.FixedTimeEquals(
        Encoding.UTF8.GetBytes(expected),
        Encoding.UTF8.GetBytes(signature));
}


The use of CryptographicOperations.FixedTimeEquals is important because signature comparison should not rely on a normal string comparison that can introduce timing-related weaknesses.

The webhook secret itself should not be stored directly in source code.

For ASP.NET Core, configuration can be used instead:
var webhookSecret =
    configuration["GitHub:WebhookSecret"];


In production, the actual value should come from protected configuration or a managed secret store.

Read the Raw Request Body
Signature validation must be performed against the original request payload.

This is important because changing the body before calculating the signature can produce a different hash.

A simplified endpoint can read the raw body:
[HttpPost]
public async Task<IActionResult> Receive()
{
    using var reader = new StreamReader(Request.Body);

    var payload = await reader.ReadToEndAsync();

    var signature =
        Request.Headers["X-Hub-Signature-256"].ToString();

    var eventName =
        Request.Headers["X-GitHub-Event"].ToString();

    // Validate signature before processing the payload.

    return Ok();
}


The important sequence is:
Receive request
      |
      v
Read raw payload
      |
      v
Validate signature
      |
      v
Identify event
      |
      v
Queue work
      |
      v
Return response


Do not treat the event body as trusted input simply because it came from a webhook endpoint.

Deserialize the Pull Request Event
After the signature is validated, the application can deserialize the payload into a suitable model.

For example:
public sealed class PullRequestEvent
{
    public string Action { get; set; } = string.Empty;

    public RepositoryInfo Repository { get; set; } = new();

    public PullRequestInfo PullRequest { get; set; } = new();
}

public sealed class RepositoryInfo
{
    public string FullName { get; set; } = string.Empty;
}

public sealed class PullRequestInfo
{
    public int Number { get; set; }

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

The actual event payload contains considerably more information, so production applications should model only the fields they need.

This keeps the application easier to maintain.

Do Not Perform Long-Running Work Inside the Webhook Request
This is one of the most important design considerations.

Suppose the application receives a pull request event and then starts:

  • Repository analysis
  • Static analysis
  • AI processing
  • Build execution
  • Test execution
  • Deployment validation

Doing all of that before returning the webhook response creates unnecessary risk.
A better design is to acknowledge the webhook quickly and move the actual work to a queue.
GitHub
   |
   v
Webhook API
   |
   | Validate
   |
   v
Queue
   |
   v
Background Worker
   |
   +--> Build
   +--> Test
   +--> Analyze
   +--> Update status


The endpoint becomes responsible for receiving and validating the event.

The worker becomes responsible for processing it.

Use an Internal Queue
For smaller ASP.NET Core applications, a background queue can be implemented using Channel<T>.
using System.Threading.Channels;

public sealed class WebhookQueue
{
    private readonly Channel<string> _channel =
        Channel.CreateUnbounded<string>();

    public ValueTask EnqueueAsync(
        string payload,
        CancellationToken cancellationToken)
    {
        return _channel.Writer.WriteAsync(
            payload,
            cancellationToken);
    }

    public IAsyncEnumerable<string> ReadAllAsync(
        CancellationToken cancellationToken)
    {
        return _channel.Reader.ReadAllAsync(
            cancellationToken);
    }
}

A hosted service can consume the queue:
public sealed class WebhookWorker
    : BackgroundService
{
    private readonly WebhookQueue _queue;

    public WebhookWorker(WebhookQueue queue)
    {
        _queue = queue;
    }

    protected override async Task ExecuteAsync(
        CancellationToken stoppingToken)
    {
        await foreach (var payload in
            _queue.ReadAllAsync(stoppingToken))
        {
            await ProcessWebhookAsync(
                payload,
                stoppingToken);
        }
    }

    private static Task ProcessWebhookAsync(
        string payload,
        CancellationToken cancellationToken)
    {
        // Perform longer-running processing here.
        return Task.CompletedTask;
    }
}


This pattern keeps the webhook endpoint responsive.
For larger systems, an external queue or message broker is usually more appropriate because it can provide persistence, retry handling, scaling, and better failure recovery.

Handle Duplicate Events

Webhook consumers should not assume that every event will be processed exactly once.
A delivery may be retried or processed more than once because of network failures, application restarts, or response problems.

The application should therefore make important operations idempotent.

For example, store a unique delivery identifier:
delivery-id
repository
event
received-at
processing-status


Before processing an event, check whether that delivery has already been handled.

Conceptually:
Receive event
     |
     v
Check delivery ID
     |
     +---- Already processed ---> Return
     |
     v
Store delivery
     |
     v
Queue processing

This prevents duplicate processing from triggering duplicate builds, notifications, or deployments.

Handle Pull Request Updates Correctly
A pull request is not a single event.
A developer can push new commits after opening the pull request.

For example:
Pull Request Opened
        |
        v
Commit Added
        |
        v
Pull Request Updated
        |
        v
Validation Runs Again


If your application validates code, the synchronize event can be important because it indicates that the pull request's branch changed.
The processing system should also avoid assuming that the first event represents the final state of the pull request.

When work is queued, consider whether processing the latest repository state is more important than processing every historical event individually.

Retry Failed Processing
Webhook reception and webhook processing are separate reliability concerns.
The webhook endpoint may successfully receive an event while the background worker later fails.

For example:
Webhook received
       |
       v
Queued successfully
       |
       v
Worker starts
       |
       v
External service unavailable
       |
       v
Processing fails


The worker should use an appropriate retry strategy for transient failures.

Do not retry every error indefinitely.

A useful classification is:
Transient error
    -> Retry

Permanent validation error
    -> Record failure

Invalid event
    -> Reject or ignore

Duplicate event
    -> Ignore safely


This makes failure handling more predictable.

Common Mistakes
Polling too frequently

A short polling interval does not make the architecture event-driven.

It simply creates more API requests.

Trusting the webhook payload
Always validate the webhook request before acting on its content.

Performing expensive work in the HTTP request
Return the webhook response quickly and move long-running work to a queue.

Ignoring duplicate delivery

Design processing to tolerate repeated events.

Subscribing to every available event
Only subscribe to events that your application actually needs.

Storing webhook secrets in source code
Use protected configuration.

Returning errors for events that do not require processing
Not every event needs to trigger work. Filter events early and keep the processing path focused.

Best Practices

  • Use webhooks when the external platform provides suitable events.
  • Subscribe only to the events your application needs.
  • Validate the webhook signature before trusting the payload.
  • Keep the webhook endpoint fast.
  • Queue long-running processing.
  • Make event processing idempotent.
  • Store delivery identifiers when duplicate handling matters.
  • Add retries for transient downstream failures.
  • Log event identifiers and processing status for troubleshooting.
  • Protect webhook secrets through secure configuration.
  • Monitor failed webhook deliveries and background processing separately.
  • Test the webhook endpoint with realistic event payloads.

Advantages
An event-driven GitHub integration provides several benefits:

  • It removes unnecessary polling requests.
  • It reduces the delay between an event and application processing.
  • It scales better when many repositories or pull requests are involved.
  • It creates a clear separation between event reception and background processing.
  • It makes integrations easier to connect to queues and workflow systems.
  • It can reduce unnecessary API usage.

The architecture is particularly useful for applications that need to respond quickly to repository activity.

Disadvantages and Limitations
Webhooks introduce their own operational responsibilities.
The application must expose an endpoint that can receive external traffic. That endpoint needs authentication or signature validation, monitoring, retry handling, and appropriate error management.

Webhook delivery also does not eliminate the need for state management. Applications may need to handle duplicate events, out-of-order processing, and events that arrive while previous work is still running.

For simple scripts that only need occasional information, polling may still be easier to implement.

The right choice depends on the workload and the capabilities of the external platform.

Troubleshooting Webhook Problems
Events are not arriving
Check that the webhook is configured for the correct repository and subscribed to the required event types.

The endpoint receives requests but rejects them

Check the webhook secret and signature validation logic.

Make sure the signature is calculated against the original request body.

Processing takes too long

Move expensive work out of the webhook request and into a background queue.
The same pull request is processed multiple times

Implement delivery-idempotency and verify that retries are not creating duplicate work.

Events arrive but the wrong action runs
Inspect the event header and the action value in the payload.

Different pull request events can have different actions.

Background processing fails

Separate webhook reception logs from worker logs. Check whether the failure is transient or permanent and apply the appropriate retry behavior.

Summary
Polling is easy to understand, but repeatedly asking GitHub whether a pull request changed is inefficient for applications that need near-event processing. GitHub webhooks provide a better event-driven model. GitHub can notify an application when relevant pull request events occur, allowing the application to validate the request, identify the event, and queue the required work. A production-ready implementation should validate webhook signatures, keep the HTTP endpoint fast, move long-running work to a queue, handle duplicate deliveries, and provide retry and monitoring mechanisms.

The important architectural shift is simple: instead of repeatedly asking whether something happened, let the system notify you when it happens. This makes pull request integrations cleaner, more responsive, and easier to scale.

HostForLIFE.eu ASP.NET Core 11.0 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



European ASP.NET Core 10.0 Hosting - HostForLIFE :: Your .NET License Check Passed Quality Assurance, but Could it Withstand a Decompiler?

clock November 16, 2026 12:25 by author Peter

The application can be unlocked with a valid license. An error occurs when a licence expires. An activation field that is empty is denied. The release appears ready, and the licensing feature passes its functional testing. But such tests only provide a response to one question: When the software operates as intended, does the licensing code function correctly?

They do not answer a second question: How easy is it to locate and modify the code that decides whether the license is accepted?

For a commercial .NET application, both questions matter. Member names and readable literals can make licensing logic straightforward to discover, even when the implementation itself is correct. Renaming, string protection, and control-flow obfuscation address different parts of that exposure.

The most useful way to evaluate these protections is to treat obfuscation as a release experiment-not a checkbox.
Define Two Acceptance Criteria

Before selecting protection settings, establish what success means.

The first criterion is behavioral:

The protected application must accept and reject the same license cases as the original application.

The second criterion concerns exposure:

The protected assembly should make the licensing decision less obvious to identify and understand through static inspection.

These criteria are related, but they are not interchangeable.

An application that still works may have received little meaningful protection. Conversely, a DLL that looks confusing in a decompiler may have broken legitimate activation, reflection, or serialization behavior.

Your release process needs evidence for both.

Build a Small Licensing Seam
Consider an application that reads a license, verifies it, and determines whether an export feature is available.

Instead of placing all that behavior in the button-click handler, separate the verified license state from the feature decision:
using System;

public sealed class VerifiedLicense
{
    public bool SignatureAccepted { get; init; }
    public string ProductCode { get; init; } = string.Empty;
    public DateTimeOffset ExpiresAtUtc { get; init; }
    public bool AllowsExport { get; init; }
}

internal static class ExportPolicy
{
    internal static bool CanExport(
        VerifiedLicense license,
        DateTimeOffset nowUtc)
    {
        if (license is null)
            return false;

        if (!license.SignatureAccepted)
            return false;

        if (!string.Equals(
            license.ProductCode,
            "REPORTING-DESKTOP",
            StringComparison.Ordinal))
        {
            return false;
        }

        if (license.ExpiresAtUtc <= nowUtc)
            return false;

        return license.AllowsExport;
    }
}


This is a policy example, not a complete licensing implementation. It does not parse a license, perform signature verification, or protect the supplied state from manipulation.

Its purpose is to provide a small, testable decision boundary.

Before obfuscation, that boundary also provides several convenient clues:

  • A class named ExportPolicy.
  • A method named CanExport.
  • Properties explaining each condition.
  • A readable product identifier.
  • A short sequence of rejection branches.

The issue is not that the developer used readable names. Readable source is valuable. The issue is whether those same explanatory details need to remain convenient in the distributed assembly.

Experiment 1: Establish the Behavioral Baseline
Start with tests that describe the licensing policy independently of the protection tool.

For the example above, the acceptance matrix might look like this:

Scenario

Expected result

Accepted signature, matching product, future expiry, export enabled

Allow

Signature rejected

Deny

License belongs to another product

Deny

License has expired

Deny

Export entitlement is absent

Deny

License object is missing

Deny

Expiry equals the evaluation time

Deny

The boundary case matters. The sample uses <=, so a license expiring exactly at the supplied time is no longer valid.

Passing time into the policy also makes these tests repeatable. They do not depend on the instant the test happens to execute.

For example:
using System;
using Xunit;

public sealed class ExportPolicyTests
{
    [Fact]
    public void LicenseAtItsExpiryTimeIsRejected()
    {
        var now = new DateTimeOffset(
            2026, 10, 8, 12, 0, 0, TimeSpan.Zero);

        var license = new VerifiedLicense
        {
            SignatureAccepted = true,
            ProductCode = "REPORTING-DESKTOP",
            ExpiresAtUtc = now,
            AllowsExport = true
        };

        Assert.False(ExportPolicy.CanExport(license, now));
    }
}


Because ExportPolicy is internal, a separate test assembly needs an intentional access arrangement, such as InternalsVisibleTo. That unit-test arrangement should not be confused with how the final protected package is tested.

The baseline tests establish the policy. Later, integration tests must exercise the actual protected application through its supported interfaces.

Experiment 2: Inspect What the Release Reveals

Compile the Release configuration and inspect the resulting assembly with a .NET decompiler.

Do this before enabling protection.

The goal is not to prove that the code can be reconstructed character for character. The goal is to understand what information is available to someone examining the shipped binary.

Use three questions:

  • Can you find the licensing path through descriptive type or member names?
  • Can you find it through literals such as product identifiers or license messages?
  • Once located, does the decision read as a small, obvious sequence of conditions?

Record the result as a baseline.

For example:
Release inspection - unprotected build

Policy type is identifiable by name: Yes
Product identifier is visible: Yes
Decision conditions are easy to follow: Yes

This record is an inspection template, not a claimed measurement of a particular product.

It gives the team something concrete to compare after protection. “We enabled obfuscation” is a configuration statement. “These licensing landmarks are no longer readable in the protected artifact” is an observation.

Experiment 3: Apply One Protection at a Time
The source tutorial combines renaming, string encryption, and control-flow protection around the licensing implementation. For an engineering evaluation, introduce those transformations separately so that failures remain attributable.

First, reduce descriptive metadata

Apply member renaming to the internal licensing implementation.

Inspect whether names such as ExportPolicy and CanExport still explain the program’s purpose.

However, do not rename every public type simply because the tool permits it. Some identifiers form runtime or integration contracts.

Reflection can resolve members by their names, and reflection-based JSON serialization collects type metadata at runtime. These dependencies need deliberate compatibility handling. learn.microsoft

Typical areas to investigate include:

  • Plug-in entry points.
  • Reflection-based factories.
  • Serialization models.
  • XAML and binding paths.
  • External APIs consumed by other assemblies.

Microsoft’s ObfuscationAttribute can communicate protection instructions to tools, but the attribute does not perform obfuscation itself. Its interpretation belongs to the selected tool. learn.microsoft

The important deliverable is a documented exclusion policy-not a growing list of unexplained exceptions.

Next, reduce readable string clues

Apply string protection to selected licensing literals.

Then repeat the inspection.

Can you still search for the product identifier? Do license-specific messages lead directly to the relevant method? Have the selected strings been transformed as expected?

String protection addresses static discoverability. It should not be interpreted as permission to distribute a durable signing secret inside the application.

A client must eventually consume values it uses. Removing a readable literal from decompiled output does not establish that the value is inaccessible during execution.

Finally, protect the decision’s control flow

Apply control-flow obfuscation to the small region that verifies or consumes licensing state.
Now inspect whether the decision remains easy to read.
Avoid requiring a particular visual result, such as a specific switch structure or number of branches. Different tools and configurations can produce different transformations.

Instead, evaluate the practical question: Does the protected method still expose the policy as an immediately understandable sequence?

Run the behavioral tests after each stage.

If the application changes behavior, isolate the first transformation that introduced the difference rather than changing several settings simultaneously.

Do Not Confuse Harder Reading With Stronger Authority
There is an architectural limit to this exercise.

Obfuscation changes how difficult it is to analyze the client. It does not make a client-side authorization result authoritative for a backend service.

Suppose the application uses a local check to enable a button that submits a premium export request. Even if the button’s licensing code is heavily protected, the server must still verify whether the caller may perform that operation.

OWASP recommends validating permissions on every request and warns against relying on client-side access controls for enforcement. cheatsheetseries.owasp

This produces a useful division of responsibilities:

Responsibility

Appropriate location

Explain why a feature is unavailable

Client interface

Evaluate a locally available license for offline operation

Client, within the offline threat model

Authorize access to a premium server operation

Server

Make distributed licensing code harder to inspect

Obfuscation stage

Offline-only software has a different constraint: it cannot ask a server to authorize every operation.

For that product model, the aim is to increase the effort required to understand and modify the application, while preserving legitimate use. Avoid describing that objective as making the client impossible to patch.

Test the Package Customers Receive

A common process mistake is to run the unit suite against the original assembly and then ship its transformed counterpart.

That proves the original implementation works. It does not prove the protected release works.

Make the final package a separate test subject.

Exercise it through the same routes customers use:

  • First activation.
  • Loading a saved license.
  • Starting with an expired license.
  • Renewing a license.
  • Attempting a feature not included in the license.
  • Handling malformed license data.
  • Running without connectivity, where supported.
  • Upgrading from an earlier release.
  • Loading plug-ins or serialized settings.

Also inspect operational behavior:

  • Startup latency.
  • License-evaluation latency.
  • Error reporting.
  • Diagnostic usefulness.
  • Required deployment files.

The source guide emphasizes functional, decompiler, and performance verification after protection. Moving those checks onto the final packaged artifact makes them part of release acceptance rather than an informal developer review.

Keep a Protection Record With Each Release

A short report can make the process reproducible:
Release protection record

Build identifier:
Protection tool and version:
Protection configuration revision:
Input assembly hashes:
Output assembly hashes:

Behavioral test result:
Packaged application test result:
Static inspection result:
Performance comparison:

Known exclusions:
Reason for each exclusion:
Reviewer:


The exclusion reasons are particularly useful.

“Excluded because activation failed” is not enough. “Preserved because the plug-in loader resolves this type by its fully qualified name” explains the dependency and supports future maintenance.

Version the protection configuration alongside other build inputs. If a release breaks, the team should be able to reproduce the transformation instead of reconstructing settings from memory.

What This Approach Actually Proves
A successful evaluation provides three kinds of evidence:

  • The protected licensing implementation preserves the intended acceptance and rejection behavior.
  • The distributed assembly reveals fewer convenient licensing landmarks.
  • The final package remains compatible with its deployment and runtime dependencies.

It does not prove that no determined analyst can recover values or modify the program.
That distinction is the foundation of a useful protection strategy.
Treat obfuscation as a measurable engineering control: establish a baseline, transform a focused region, verify the behavior, inspect the result, and retain the evidence with the release.
Your license check should not merely pass QA. The version you ship should also justify the protection claims you make about it.

HostForLIFE.eu ASP.NET Core 11.0 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



European ASP.NET Core 10.0 Hosting - HostForLIFE :: What Does .NET 11 Offer? A Guide for Developers on the Most Recent Release?

clock November 13, 2026 10:51 by author Peter

On November 10, 2026, Microsoft formally released.NET 11, which is compatible with Windows, Linux, and macOS and offers yet another significant set of enhancements to the.NET ecosystem. The .NET Runtime, SDK, libraries, ASP.NET Core, Blazor, Entity Framework Core, .NET MAUI, Windows Forms, WPF, and the C# language are all improved in this release.

This is why improving build performance should start with finding where the time is going. .NET 11 provides a newer build environment, but upgrading alone does not guarantee faster builds. Existing project structure and build configuration still have a major impact on how much work MSBuild performs.

How MSBuild Actually Builds a Solution
MSBuild is the build engine used by .NET projects to coordinate the work required to produce an application or library.

A simplified build looks like this:
MSBuild starts
      |
      v
Project evaluation
      |
      v
Dependency graph
      |
      v
Restore
      |
      v
Compilation
      |
      v
Analyzers
      |
      v
Generated files
      |
      v
Copy / publish / packaging
      |
      v
Output


Not every build spends the same amount of time in every stage.
For a small application, compilation may dominate the build.
For a large solution, project evaluation and dependency management can become significant.
A solution with dozens or hundreds of projects can also spend considerable time determining project relationships before compilation begins.
This is why looking only at compiler performance often leads to the wrong optimization.

Start by Measuring the Build

The first rule of build optimization is simple: measure before changing the project.

If a build takes 90 seconds, you need to know whether those 90 seconds are spent compiling C#, evaluating projects, running analyzers, restoring packages, or executing custom build targets.

Run a normal build first:
dotnet build

Then increase the amount of build information when investigating the problem:

dotnet build --verbosity diagnostic

Diagnostic verbosity produces a large amount of output, so it is not something you normally want in every build.

Use it when investigating a specific performance problem.

For larger solutions, binary logs are often more useful because they allow the build process to be inspected after the build completes.
dotnet build -bl

The resulting binary log can be opened with an MSBuild log viewer and used to identify expensive targets and project evaluation.

The goal is not to collect logs for their own sake.

The goal is to answer a practical question:

What work is taking most of the build time?
Project Evaluation Can Become Expensive

Before MSBuild compiles your C# code, it evaluates the project files.

Consider a project file containing multiple property groups, item groups, imports, conditions, package references, and custom targets.

MSBuild must process these instructions before it knows exactly what work needs to be performed.

In a large solution, this happens across many projects.

A project file can therefore become expensive even when the actual C# compilation is relatively small.

For example:
<PropertyGroup>
    <EnableDefaultItems>true</EnableDefaultItems>
    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
</PropertyGroup>

<ItemGroup>
    <PackageReference Include="Example.Package" Version="1.0.0" />
</ItemGroup>


This is normal.

The problem appears when projects accumulate large amounts of conditional configuration and repeated MSBuild logic over time.

Common sources include:

  • Large Directory.Build.props files
  • Large Directory.Build.targets files
  • Repeated ItemGroup definitions
  • Complex conditions
  • Custom targets
  • Generated project files
  • Excessive imports
  • Unnecessary project references

If project evaluation is taking significant time, reducing unnecessary MSBuild work can have a larger effect than changing compiler settings.

Check Directory.Build.props and Directory.Build.targets

Central MSBuild files are useful because they allow common settings to be shared across many projects.

For example:
Solution
│
├── Directory.Build.props
├── Directory.Build.targets
│
├── App
│   └── App.csproj
│
├── Services
│   └── Services.csproj
│
└── Infrastructure
    └── Infrastructure.csproj


The benefit is consistency.

The downside is that a change in one central file can affect every project below it.

Suppose a Directory.Build.targets file executes a custom task for every project:
<Target Name="GenerateMetadata" BeforeTargets="Build">
    <Exec Command="some-tool generate" />
</Target>

If the solution contains many projects, that command may run many times.

The application may still build correctly, but the repeated work can become expensive.

Before adding custom targets to a central MSBuild file, ask whether every project really needs to execute them.

Avoid Building Projects That Do Not Need to Build

Project references create a dependency graph.

For example:
Web
 |
 +-- Application
       |
       +-- Domain
       |
       +-- Infrastructure


When Web is built, MSBuild needs to consider the referenced projects.

This is expected.
The problem occurs when the dependency graph contains unnecessary references.

For example, if Domain references Infrastructure only because one utility class was placed in the wrong project, a change in Infrastructure can cause more projects to rebuild.

Keep dependency direction intentional.

A common architecture is:
Web
 |
Application
 |
Domain

with Infrastructure implementing interfaces defined by the Application or Domain layers rather than creating unnecessary reverse dependencies.

A clean project graph can reduce both build work and architectural coupling.

ProjectReference Is More Expensive Than It Looks

A ProjectReference is not simply a namespace import.

It tells MSBuild that one project depends on another project as part of the build.

Consider:
<ItemGroup>
    <ProjectReference Include="..\Shared\Shared.csproj" />
</ItemGroup>

When the referenced project changes, dependent projects may need to rebuild.
This is useful when the dependency is real.

However, adding project references for convenience can gradually create a large build graph.

If a project only needs a small set of reusable types, consider whether the dependency is architecturally correct.

The goal is not to remove project references blindly.
The goal is to avoid unnecessary build relationships.

Package Restore and Build Are Different Problems
Another common mistake is assuming every slow build is caused by compilation.

Consider:
dotnet restore
dotnet build --no-restore


If the second command is fast but a normal build is slow, restore may be part of the problem.

This distinction is useful in CI environments.

A pipeline might perform restore, build, test, and publish in separate stages.

If every stage repeats package work unnecessarily, the pipeline can spend considerable time doing work that could have been reused.

Caching NuGet packages in CI can help, but caching should be based on the actual package restore behavior rather than added blindly.

Analyzers Can Add Significant Build Time

Static analyzers are valuable because they detect problems before code reaches production.

However, analyzers also consume CPU and memory.

A project may compile quickly but spend much longer running analyzers.

This is particularly noticeable in large solutions with many source files.

If diagnostic logs show that analyzers consume a significant portion of build time, review which analyzers are enabled and where they are applied.

Do not disable all analyzers simply to make builds faster.

Instead, identify the expensive analyzers and determine whether they need to run for every project and every build.

For example, some checks may be appropriate during CI but unnecessary for every local development build.

The right solution depends on the team's quality requirements.

Incremental Builds Are Important

MSBuild is designed to avoid repeating work unnecessarily.

This is called incremental building.

If a developer changes one source file, the build system should not need to perform every possible operation from scratch.

A good incremental build looks roughly like this:

Change one file
      |
      v
Identify affected project
      |
      v
Compile required work
      |
      v
Run required targets
      |
      v
Produce updated output


A poorly designed custom target can break this efficiency.

For example, a target that always runs because its inputs and outputs are not declared correctly can execute during every build.

That creates unnecessary work.

If you maintain custom MSBuild targets, understand inputs and outputs and make the target incremental where possible.

Custom Exec Commands Need Special Attention

Custom shell commands are convenient.

For example:
<Target Name="GenerateClient" BeforeTargets="Build">
    <Exec Command="node generate-client.js" />
</Target>


The problem is that MSBuild does not automatically know whether the generated output is already up to date.

If the command runs every time, it can slow down local development significantly.

A better target declares the files that it consumes and produces when appropriate:

<Target Name="GenerateClient"
        BeforeTargets="Compile"
        Inputs="client-schema.json"
        Outputs="generated\Client.g.cs">

    <Exec Command="node generate-client.js" />
</Target>


Now MSBuild has information it can use to determine whether the target needs to run.

The exact implementation depends on the tool and generated files, but the principle is important: build systems work better when dependencies are explicit.

Generated Code Can Affect Build Performance

Source generators and other code-generation mechanisms can reduce manual work, but they still participate in the build.
If a generator processes a large amount of input on every compilation, its cost can become noticeable.

When investigating slow builds, include generated-code work in your analysis.

Ask:

  • What generates the code?
  • When does generation happen?
  • Does it process the whole solution?
  • Can the generated output be reused?
  • Is the generator running for projects that do not need it?

The answer can reveal build time that would otherwise be incorrectly attributed to the compiler.

CI Builds Need Separate Investigation

A build that is fast locally can still be slow in CI.

The environment is different.

CI may have:

  • A clean workspace
  • Cold package caches
  • Fewer CPU resources
  • Different SDK configuration
  • Different build parameters
  • Additional analyzers
  • Test and coverage instrumentation
  • Container overhead


Therefore, measure local and CI builds separately.

Do not optimize local builds and assume the CI pipeline will automatically improve.

A useful CI investigation separates the stages:
Restore
   |
   v
Build
   |
   v
Test
   |
   v
Coverage
   |
   v
Publish

This makes it easier to identify which stage is responsible for the slowdown.
A Practical Process for Finding Slow Build Work

When a .NET solution starts building slowly, use this process.

Step 1: Establish a Baseline

Record the normal build time.

Run the same command several times so that one unusual build does not distort the result.

Step 2: Capture a Binary Log

Use:
dotnet build -bl

Inspect the resulting build timeline.

Step 3: Find the Slowest Projects

Determine which projects consume the most build time.

Do not assume the largest project is automatically the slowest.

Step 4: Separate Evaluation From Compilation
Check whether the problem occurs before compilation begins or during compilation.

This distinction determines where you should investigate next.

Step 5: Inspect Custom Targets

Look for targets that run on every build.

Pay particular attention to Exec commands, code generation, file copying, and external tools.

Step 6: Review Project Dependencies

Look for unnecessary ProjectReference relationships and dependency chains.

Step 7: Test Incremental Builds

Change a single source file and observe how much work MSBuild performs.

If a small change triggers large amounts of unrelated work, investigate the dependency graph and custom targets.

Common Mistakes
Increasing Hardware Without Finding the Problem

More CPU can help compilation, but it does not fix inefficient MSBuild configuration.

First determine what the build is actually doing.

Disabling Analyzers Globally
This may reduce build time but also removes useful quality checks.

Identify expensive analyzers instead of disabling the entire analysis system.

Adding More Caching
Caching helps when the same work can be reused.
It does not fix a build that is repeatedly performing unnecessary work.

Using Custom Targets Without Incremental Inputs
A target that runs every time can become one of the biggest sources of build overhead.

Define inputs and outputs where appropriate.

Optimizing Only the Compiler

Compilation is only one part of a modern .NET build.

Project evaluation, restore, analyzers, generation, and custom tasks can all contribute to the total build time.

HostForLIFE.eu ASP.NET Core 11.0 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.

 



European ASP.NET Core 10.0 Hosting - HostForLIFE :: A Useful Field Guide to Obfuscating.NET Assemblies That Serialize to JSON and XML

clock November 9, 2026 11:08 by author Peter

Target platform: C# Corner Audience: .NET developers, solution architects, and release engineers who ship commercial or licensed desktop/server software Prerequisites: Working knowledge of C#, reflection, and at least one serializer (System.Text.Json, Newtonsoft.Json, or XmlSerializer)

Why this topic keeps coming back?

Every few months someone posts the same question on a .NET forum: "I obfuscated my app and now my API calls return empty objects." The symptom is always the same — no crash, no exception, just silently null properties or 0 values in objects that were previously populated correctly. The developer assumes the obfuscator is broken. It isn't. The obfuscator did exactly what it was told to do: it renamed everything.

Serialization is one of the few places in .NET where the name of a symbol is part of your application's public contract. If you rename a property called CustomerName to a, the JSON serializer will happily go looking for a key called "a" in the incoming payload. The payload doesn't contain "a". The property stays null. No exception is thrown because, from the serializer's perspective, the field is simply optional.

This article walks through the underlying mechanics, the failure modes, and a production-ready strategy for protecting serialization-heavy assemblies without breaking them.

The core mechanism: reflection is the bridge
All three mainstream .NET serializers use reflection to discover what to read and write.

When System.Text.Json deserializes an object, it walks the type's properties at runtime. For each property it needs a name. That name comes from one of two places, in priority order:

  • An explicit contract attribute — [JsonPropertyName("customer_id")], [JsonProperty("customer_id")], [XmlElement("CustomerID")], [DataMember(Name = "...")].
  • The CLR metadata name — the actual symbol name stored in the assembly's metadata tables.

The first source is a string literal baked into the attribute blob. The second is the symbol itself, and it's exactly what an obfuscator rewrites.

This distinction is the entire foundation of the safe obfuscation strategy:

  • Properties with explicit name attributes are safe to rename. The attribute string survives renaming, and the serializer reads the string, not the symbol.
  • Properties without explicit name attributes are not safe to rename. The serializer reads the symbol, and the symbol no longer matches the payload key.

It really is that simple. Everything else in this article is a consequence of that rule.

A concrete example
Consider this DTO, which a hypothetical order service deserializes from an external partner API:
public class PartnerOrderDto
{
    [JsonPropertyName("order_ref")]
    public string OrderReference { get; set; }

    [JsonPropertyName("customer_name")]
    public string CustomerName { get; set; }

    public decimal TotalAmount { get; set; }

    public string CurrencyCode { get; set; }
}

Now compare the incoming JSON:

{
  "order_ref": "PO-99182",
  "customer_name": "Northwind Traders",
  "TotalAmount": 1450.00,
  "CurrencyCode": "USD"
}


Two of the four properties have explicit attributes. Two rely on their symbol names. If you obfuscate this assembly with default settings:

  • OrderReference and CustomerName will be renamed, but the serializer still reads "order_ref" and "customer_name" from the attributes. ✅ These bind correctly.
  • TotalAmount and CurrencyCode will be renamed to something like a and b. The serializer now looks for "a" and "b" in the payload. ❌ These return 0 and null.

The bug is invisible in unit tests that only exercise the two attributed properties. It surfaces only in production, against real partner traffic.

The polymorphic problem
Polymorphic deserialization is where even experienced developers get caught out, because the failure mode is different: instead of silent data loss, you get a hard exception.

System.Text.Json
System.Text.Json handles polymorphism through [JsonPolymorphic] and [JsonDerivedType]:
[JsonPolymorphic(TypeDiscriminatorPropertyName = "$type")]
[JsonDerivedType(typeof(StandardAccount), "standard")]
[JsonDerivedType(typeof(PremiumAccount), "premium")]
public abstract class AccountBase
{
    public string AccountId { get; set; }
}

Here the discriminators "standard" and "premium" are explicit string literals. They survive obfuscation. But the class names StandardAccount and PremiumAccount are not used as discriminators in this configuration — they're only used as typeof() arguments, which are resolved at compile time and encoded as metadata tokens. If the obfuscator renames the classes, the typeof() references are updated consistently, so this works.

The failure case is when you don't specify explicit discriminators and rely on the default, which uses the type's full name. Then renaming the class breaks the resolution and you get a JsonException at runtime.

Newtonsoft.Json $type
Newtonsoft's TypeNameHandling is more dangerous. With TypeNameHandling.All or TypeNameHandling.Objects, the serializer writes the assembly-qualified type name into a $type property in the JSON itself:
{
  "$type": "MyApp.Contracts.PremiumAccount, MyApp.Contracts",
  "AccountId": "ACC-001"
}


This means the class name and the assembly name are part of the wire format. Renaming either one breaks deserialization for any payload produced by an older, un-obfuscated build — including payloads from other services that haven't been updated. This is the scenario where people typically abandon obfuscation entirely.

The correct fix is to implement a custom SerializationBinder that maps stable string IDs to types, and to configure the serializer to use that binder on both ends. Once the binder is in place, the $type value is no longer a raw type name — it's a key the binder understands — and the type itself can be freely renamed.

XmlSerializer

XmlSerializer deserves its own warning. When you construct an XmlSerializer at runtime, it generates a temporary assembly that contains the serialization logic. That generated assembly is built from reflection data, including type names. If you rename a type that appears inside an [XmlInclude] attribute, the generated serializer will look for a type that no longer exists under that name and throw InvalidOperationException during construction — often before any data is read.

[XmlInclude] is the specific thing to watch for:
[XmlInclude(typeof(StandardAccount))]
[XmlInclude(typeof(PremiumAccount))]
public abstract class AccountBase { ... }

The typeof() references are rewritten consistently by a good obfuscator, so this usually works. What breaks is when the XML itself carries type names — for example, when you serialize an abstract-typed collection and the runtime emits xsi:type attributes. Those are written using the CLR type name, and if that name changes, round-trip serialization between old and new builds fails.

A strategy that works

The strategy that holds up across all three serializers has three parts.

1. Make contracts explicit

Go through every DTO and add explicit name attributes to every property that participates in serialization. This is tedious, but it converts the problem from "the obfuscator must know which properties are serialized" into "the compiler knows, and the obfuscator doesn't need to."
public class PartnerOrderDto
{
    [JsonPropertyName("order_ref")]
    [JsonProperty("order_ref")]
    [XmlElement("OrderRef")]
    public string OrderReference { get; set; }

    [JsonPropertyName("customer_name")]
    [JsonProperty("customer_name")]
    [XmlElement("CustomerName")]
    public string CustomerName { get; set; }

    [JsonPropertyName("total_amount")]
    [JsonProperty("total_amount")]
    [XmlElement("TotalAmount")]
    public decimal TotalAmount { get; set; }

    [JsonPropertyName("currency_code")]
    [JsonProperty("currency_code")]
    [XmlElement("CurrencyCode")]
    public string CurrencyCode { get; set; }
}


Once this is done, all four properties can be renamed safely. The obfuscator scrambles the C# symbols; the serializers read the attribute strings.

The cost is verbosity. The benefit is that obfuscation becomes a no-op with respect to serialization correctness.

2. Isolate contracts into their own namespace

If you can't (or won't) attribute every property, the next best thing is to put all DTOs into a dedicated namespace — MyCompany.Contracts, for example — and configure the obfuscator to skip that namespace entirely.

This is a coarser instrument than attribute-based exclusion, but it's easy to reason about and easy to audit: anything in MyCompany.Contracts is a serialization contract and is never renamed; anything outside it is fair game.

The downside is that the contract namespace itself isn't protected. A competitor can still read your DTO shapes. But DTOs are rarely the valuable IP — the business logic that consumes them is. And that logic lives in a different namespace.

3. Protect the engine, not the contract

This is the key insight that makes the whole approach viable: excluding DTOs from renaming does not meaningfully reduce your protection.

The DTOs are the interface. They're designed to be seen — they're documented in your API reference, they're visible in every network trace, and they're usually derived from a published schema. There's nothing to protect.

The valuable parts of the assembly are:

  • The business logic that processes deserialized data.
  • The algorithms that compute results.
  • The string literals that contain API keys, connection strings, and internal endpoints.
  • The control flow that implements proprietary decision-making.


All of these can receive full obfuscation — identifier scrambling, control-flow flattening, string encryption — without touching the contract surface. A competitor who decompiles your assembly will see a clean, readable PartnerOrderDto class sitting next to an incomprehensible engine class full of state-machine dispatch tables and encrypted strings. That's the desired outcome.

Testing: what to actually verify
Obfuscation bugs are almost always runtime bugs, so unit tests that run against unobfuscated code will not catch them. You need to test the obfuscated artifact.

A minimal but effective test suite has three components:
Round-trip tests. Populate every DTO with distinctive values, serialize to JSON and XML, deserialize back, and assert deep equality. Run this against the obfuscated build, not the debug build.

Contract fixtures. Save real JSON and XML payloads from your external partners (or from your own API spec) as test fixtures. Deserialize them against the obfuscated build and assert that every expected property is populated. This catches the silent-null failure mode that round-trip tests miss, because round-trip tests use your own serialized output as input, which will always match whatever the obfuscator produced.

Polymorphic dispatch tests. Explicitly construct payloads with each discriminator value and verify that the correct concrete type is instantiated and that its derived properties are populated. This catches the exception-based failures.

Run all three in CI against the obfuscated artifact before it's promoted to release.

A quick reference: symptom → cause → fix

Symptom

Likely cause

Fix

Property is null or default after deserialization, no exception

Un-attributed property was renamed

Add explicit name attribute, or exclude DTO from renaming

JsonException: Could not resolve polymorphic type

Class name was renamed and no explicit discriminator was set

Add explicit discriminator string via [JsonDerivedType]

InvalidOperationException during XmlSerializer construction

Renamed type referenced in [XmlInclude] or xsi:type

Exclude the type from renaming

Newtonsoft $type deserialization fails across builds

Assembly-qualified type name embedded in payload was mutated

Implement a custom SerializationBinder with stable IDs

Works in debug, fails in release

Obfuscation applied only in release configuration

Add obfuscated artifact to CI test matrix

Closing thoughts
The tension between obfuscation and serialization is real, but it's narrower than it first appears. It only affects the names of serialized symbols — not their behavior, not their types, and not the logic that uses them. Once you internalize the rule that "explicit attribute strings survive renaming, implicit symbol names do not," the correct configuration becomes obvious. Attribute your contracts, isolate them if you can't attribute them, and let the obfuscator do its real work on the parts of the assembly that actually contain intellectual property.

The result is an assembly that decompiles to a readable contract surface surrounded by unreadable implementation — which is exactly what a well-protected .NET application should look like.

*The author works on the Rustemsoft team and contributes to the Opaquer .NET Obfuscator documentation. Feedback and corrections are welcome in the comm

HostForLIFE.eu ASP.NET Core 11.0 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



European ASP.NET Core 10.0 Hosting - HostForLIFE :: Incrementally Reading CBOR data in .NET 11

clock November 3, 2026 11:20 by author Peter

Data is often received by applications via files, IoT devices, APIs, and other services. Loading the full payload into memory before processing it might result in more memory utilization and a slower response as the data is big. Concise Binary Object Representation, or CBOR, is a binary data format intended to compactly represent structured data. It is helpful when applications need to transmit data effectively, particularly when processing overhead and payload size are important considerations.

In .NET, developers can work with CBOR data using APIs provided by the System.Formats.Cbor package. When data arrives in smaller chunks, incremental processing can help an application avoid waiting for the complete payload before beginning its work.

This article explains how CBOR works, how to read CBOR data incrementally in .NET, and how to handle incomplete input safely. The examples focus on the core parsing concepts and the practical considerations involved in processing streamed binary data.

One important detail: the availability of specific APIs depends on the target framework and package version. Verify the APIs supported by the version used in your project rather than assuming that every CBOR feature is built into .NET 11.

What Is CBOR?

CBOR is a binary serialization format standardized for representing structured data. It supports values such as integers, strings, byte strings, arrays, maps, Boolean values, and null.

Unlike JSON, which represents data using readable text, CBOR encodes values in a binary format.

For example, a JSON message might look like this:
{
  "deviceId": 42,
  "temperature": 26.5,
  "active": true
}


CBOR can represent the same information in a compact binary structure.

The binary representation is not intended to be read directly by a person. An application uses a CBOR decoder to interpret its contents.

CBOR vs. JSON

Feature

CBOR

JSON

Representation

Binary

Text

Human readability

Requires decoding tools

Readable without special tools

Data types

Supports binary values and additional native data types

Primarily supports objects, arrays, strings, numbers, Booleans, and null

Payload size

Can be smaller for suitable data

Depends on the structure and textual representation

Debugging

Often requires a decoder or specialized tools

Easy to inspect in logs and text editors

Common use cases

Binary protocols, constrained devices, structured binary messages

Web APIs, configuration files, and general data exchange

CBOR is not automatically smaller or faster for every payload. The result depends on the data, encoding choices, and application implementation.

Why Read CBOR Incrementally?
Consider an application that receives sensor information from thousands of devices. Each device sends a CBOR message containing its identifier, timestamp, and measurements.
A straightforward implementation might collect the entire message into a byte array and then decode it.
For small messages, this is often sufficient. However, large messages or many concurrent requests can increase memory pressure.
Incremental reading allows an application to process data as it becomes available.

The main advantages include:

  • Processing data without requiring one large input buffer.
  • Starting work before the entire input has arrived.
  • Managing memory more carefully for large payloads.
  • Supporting network protocols that deliver data in multiple chunks.

Incremental reading does not mean that every individual CBOR value can be processed before its encoding is complete. The parser still needs enough bytes to recognize and decode the current value. It is also important to distinguish incremental parsing from network streaming. A CBOR decoder processes encoded values, while the network layer determines how bytes arrive.

Understanding CBOR Parsing in .NET

The System.Formats.Cbor package provides the CborReader class for reading CBOR data.
A reader can decode values from a byte buffer. For example, the following program reads a CBOR array containing a device identifier, a temperature, and a status flag.

First, install the package if it is not already available in your project:
dotnet add package System.Formats.Cbor

The package version should be selected according to your project's target framework and dependency requirements.

Reading a Complete CBOR Message
The following example creates a CBOR message and reads its values.
using System;
using System.Formats.Cbor;

byte[] payload;

var writer = new CborWriter();

writer.WriteStartArray(3);
writer.WriteInt32(42);
writer.WriteDouble(26.5);
writer.WriteBoolean(true);
writer.WriteEndArray();

payload = writer.Encode();

var reader = new CborReader(payload);

int arrayLength = reader.ReadStartArray()
    ?? throw new FormatException("An array length is required.");

if (arrayLength != 3)
{
    throw new FormatException("Unexpected CBOR array length.");
}

int deviceId = reader.ReadInt32();
double temperature = reader.ReadDouble();
bool active = reader.ReadBoolean();

reader.ReadEndArray();

if (reader.BytesRemaining != 0)
{
    throw new FormatException("Unexpected trailing CBOR data.");
}

Console.WriteLine($"Device ID: {deviceId}");
Console.WriteLine($"Temperature: {temperature}");
Console.WriteLine($"Active: {active}");


The writer is included to make the example self-contained. In a real application, the payload would usually come from a file, a network connection, or another service.

The reader processes the array in the order in which its values were encoded.

The length check helps reject unexpected structures. The final check ensures that the example does not silently ignore extra bytes after the expected message.

This example reads a complete payload. To process data incrementally, the application needs to handle incomplete input and preserve the bytes that have not yet been consumed.

Handling CBOR Data That Arrives in Chunks

A network stream does not guarantee that a complete CBOR value will arrive in a single read operation.

For example, a message may contain 100 bytes, but the first network read may return only 20 bytes. The remaining bytes may arrive in later reads.

The application must not assume that one read returns one complete message.

A common approach is to maintain a buffer, append newly received bytes, and parse complete values while retaining incomplete data.

For low-level incremental parsing, .NET provides System.Formats.Cbor reader APIs, but the exact approach depends on the package version and the required CBOR structure.

The following example demonstrates the buffering principle using a stream and a memory buffer. It collects one complete payload before decoding it, so it is useful for understanding partial reads but is not a fully incremental CBOR parser.
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

static async Task<byte[]> ReadPayloadAsync(
    Stream stream,
    int maximumSize,
    CancellationToken cancellationToken = default)
{
    using var buffer = new MemoryStream();
    byte[] chunk = new byte[4096];

    while (true)
    {
        int bytesRead = await stream.ReadAsync(
            chunk.AsMemory(),
            cancellationToken);

        if (bytesRead == 0)
        {
            break;
        }

        if (buffer.Length + bytesRead > maximumSize)
        {
            throw new InvalidDataException(
                "The payload exceeds the permitted size.");
        }

        await buffer.WriteAsync(
            chunk.AsMemory(0, bytesRead),
            cancellationToken);
    }

    return buffer.ToArray();
}


This helper reads until the stream ends and rejects payloads larger than the configured limit. It is suitable only when the stream's end indicates the end of the payload. If the connection stays open or contains multiple messages, the application needs a framing protocol that identifies where each message ends.

The helper also retains the complete payload in memory. For large messages, a more advanced parser should process complete CBOR values as bytes arrive.

Using SequenceReader and Pipelines for Incremental Processing

For high-throughput applications, System.IO.Pipelines can help manage incoming bytes efficiently. A pipeline provides a PipeReader that exposes available input as a ReadOnlySequence<byte>. The application can examine the available data, process what it understands, and retain the remainder for the next read.

The general process is:

  • Read available bytes from the pipeline.
  • Attempt to decode the next CBOR value.
  • Record how many bytes were successfully consumed.
  • Preserve incomplete bytes for the next read.
  • Release consumed memory and continue processing.

SequenceReader<byte> can help navigate a sequence of bytes, but it does not decode CBOR values by itself. The CBOR parser must still understand the format's encoding rules.

A production implementation should use the incremental or sequence-based APIs supported by the selected CBOR library version. If those APIs are unavailable, use a well-tested parser or buffer complete framed messages before decoding them.

Avoid manually implementing the CBOR binary format unless you have a strong reason to do so. Incorrect handling of lengths, nesting, or special values can lead to parsing errors and security problems.

Handling Incomplete and Invalid Data
Incremental parsers must distinguish between incomplete input and invalid input.

Suppose a message begins with an array declaration but ends before all the array elements arrive. The data may be valid but incomplete.

By contrast, a message may contain a value that does not match the expected structure. That is a validation failure rather than a temporary lack of bytes.

A robust implementation should account for the following situations:

Situation

Recommended Handling

More bytes are needed

Preserve the incomplete input and read more data

Invalid CBOR encoding

Reject the message and record an appropriate error

Unexpected value type

Reject the message if it violates the expected schema

Payload exceeds the configured limit

Stop processing and reject the input

Unexpected trailing bytes

Reject the message or handle them according to the protocol

Network connection closes early

Treat the message as incomplete if the required data has not arrived

The parser's exception behavior depends on the specific API. Do not treat every parsing exception as proof that more bytes are needed. Some exceptions indicate malformed data and should not trigger endless retries.

Common Mistakes to Avoid
Assuming One Read Returns the Entire Message

A stream read may return fewer bytes than requested. Always account for partial reads.

Loading Unlimited Data Into Memory

An application that accepts unlimited payload sizes can consume excessive memory. Configure a maximum message size and enforce it while reading.

Ignoring Message Boundaries

CBOR describes data values, but a network protocol must still establish how messages are separated. Use an explicit length prefix, a protocol-defined boundary, or another reliable framing mechanism.

Confusing Incomplete Input With Invalid Input

Incomplete data may become valid when additional bytes arrive. Invalid data should be rejected rather than retried indefinitely.

Accepting Unexpected Data
Check that decoded values have the expected types, lengths, and structure. Reject trailing bytes when the protocol expects exactly one message.

Best Practices for Production Applications

Use these practices when building a CBOR-processing service:

  • Set a maximum payload size based on the application's requirements.
  • Use asynchronous stream operations for network-bound workloads.
  • Preserve unconsumed bytes between parsing operations.
  • Validate the decoded structure before using its values.
  • Handle cancellation and network failures explicitly.
  • Avoid logging complete payloads when they may contain sensitive information.
  • Test with fragmented input, malformed messages, and unexpected value types.
  • Use a maintained CBOR library rather than writing a custom decoder.
  • Measure memory usage and throughput under realistic workloads before choosing a buffering strategy.

These practices improve reliability and help protect the application from malformed or unexpectedly large inputs.

Advantages and Disadvantages
Advantages

Incremental CBOR processing can reduce the need to buffer an entire payload before starting useful work. It can improve memory management and support applications that receive data gradually.

It is particularly useful when processing large messages or handling many concurrent connections.

Disadvantages
Incremental parsing requires more careful buffer management than decoding a complete byte array. Developers must handle incomplete input, message boundaries, parser state, and error recovery correctly.

The implementation can also become more complex if the chosen CBOR library does not expose the required sequence-based or incremental APIs.

Summary

CBOR provides a compact binary format for structured data, and .NET applications can decode it with the System.Formats.Cbor package. For small payloads, reading the complete message into memory and using CborReader is often the simplest solution. For larger or continuously arriving payloads, incremental processing can reduce buffering overhead, but it requires careful handling of incomplete data and message boundaries.

The most important considerations are to choose APIs supported by your package version, enforce payload limits, validate the decoded structure, and distinguish incomplete input from malformed data. Start with a simple implementation that matches your message sizes and performance requirements. Introduce incremental parsing when the application's workload justifies the additional complexity.

HostForLIFE.eu ASP.NET Core 11.0 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



About HostForLIFE.eu

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

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


Month List

Tag cloud

Sign in