Asendia Tracking & .NET Shipping Integration

Asendia Tracking API Integration in C#:
Regional API Patterns for .NET Tracking

A practical account-specific integration design for C#, ASP.NET Core and multi-carrier shipping software.

September 2026 • 16 min read • By Kshitij Mehta

Asendia tracking integration can expose parcel updates alongside other carrier services, but the available interface depends on the selected Asendia product, region and customer account. Confirm the current API reference, authentication, request fields and event model before implementation. A tracking adapter can then validate references, call the documented service, handle errors and normalize returned events for the application.

API scope: The OAuth, request and DTO snippets below are illustrative patterns, not a verified universal Asendia API contract or evidence of a deployed connector. Use the product and account documentation that applies to the project. For example, Asendia Sync provides a product-specific API reference; its availability and contract should not be assumed for every region or service.

The code below uses ExampleShippingApp as a fictional name for a possible .NET adapter boundary. It is not evidence of a deployed Asendia connector. The authentication and payload examples are conditional patterns only; replace them with the current interface documented for the specific product and account.

Key Takeaways
  • Keep the selected Asendia transport and authentication inside a dedicated carrier client.
  • Use typed configuration and a configured HttpClient; follow the selected API reference for required settings.
  • Use OAuth client credentials only when the selected Asendia API documentation requires that flow.
  • Build the tracking request from the documented schema; do not assume a universal bulk-tracking model.
  • If the response includes multiple timestamped events, use the documented timestamp and ordering rules to select the latest update.
  • Normalize the status values actually returned by the selected interface into application states.
  • Return dedicated no-data and error results when tracking information is unavailable.
  • Keep customer-specific credentials, account identifiers and environment details out of public documentation.

1. Where Asendia Tracking Fits in a Shipping Platform

The application should ask a tracking service for shipment information rather than knowing how Asendia authentication or JSON requests work. The carrier client owns those details and returns an application-level result.


ExampleShippingApp
      ↓
Tracking Service
      ↓
IAsendiaTrackingClient
      ↓
Documented Auth Method
      ↓
Asendia Tracking API
      ↓
TrackingBulkResponse
      ↓
TrackingInfo
      ↓
Standard TrackingResult
      ↓
UI / API
                

2. Create a Dedicated Asendia Tracking Client

A sample .NET application can place provider-specific tracking logic behind an interface such as IAsendiaTrackingClient and inject its configured dependencies through the constructor.


public class AsendiaTrackingClient
    : IAsendiaTrackingClient
{
    private readonly HttpClient _httpClient;
    private readonly AsendiaCredentials _credentials;
    private readonly ILogger<AsendiaTrackingClient> _logger;

    public AsendiaTrackingClient(
        HttpClient httpClient,
        IOptions<AsendiaCredentials> credentials,
        ILogger<AsendiaTrackingClient> logger)
    {
        _httpClient = httpClient;
        _credentials = credentials.Value;
        _logger = logger;
    }
}
                

3. Start the Tracking Operation with Cancellation

A tracking method can validate its input, construct the request required by the selected API, apply the documented authentication and map the response. Unexpected failures should be logged and converted into a stable application error result.


public async Task<TrackingInfo> GetTrackingAsync(
    string trackingNumber,
    CancellationToken cancellationToken = default)
{
    try
    {
        string cleanTrackingNumber =
            trackingNumber?.Trim().TrimEnd(',')
            ?? string.Empty;

        string accessToken =
            await GetAccessTokenAsync(
                cancellationToken)
            .ConfigureAwait(false);

        var requestObj =
            new TrackingBulkRequest
            {
                trackingReferences =
                    new[] { cleanTrackingNumber }
            };

        string json =
            JsonConvert.SerializeObject(
                requestObj);

        using var request =
            new HttpRequestMessage(
                HttpMethod.Post,
                _credentials.ApiEndpoint)
            {
                Content =
                    new StringContent(
                        json,
                        Encoding.UTF8,
                        "application/json")
            };

        request.Headers.Add(
            "X-Example-Access-Key",
            _credentials.AccessKey);

        request.Headers.Add(
            "X-Example-API-Key",
            _credentials.ApiKey);

        request.Headers.Authorization =
            new AuthenticationHeaderValue(
                "Bearer",
                accessToken);

        using HttpResponseMessage response =
            await _httpClient.SendAsync(
                request,
                cancellationToken)
            .ConfigureAwait(false);

        string respJson =
            await response.Content
                .ReadAsStringAsync()
                .ConfigureAwait(false);

        if (!response.IsSuccessStatusCode)
        {
            _logger.LogError(
                "Asendia API error: {StatusCode} - {Response}",
                response.StatusCode,
                respJson);

            return CreateErrorTrackingInfo(
                $"API error: {response.StatusCode}");
        }

        var bulkResponse =
            JsonConvert.DeserializeObject<TrackingBulkResponse>(
                respJson);

        return MapToTrackingInfo(
            bulkResponse,
            cleanTrackingNumber);
    }
    catch (Exception ex)
    {
        _logger.LogError(
            ex,
            "Asendia tracking failed for {TrackingNumber}",
            trackingNumber);

        return CreateErrorTrackingInfo(
            "Error fetching tracking data");
    }
}
                

4. Implement the Documented Authentication Flow

The code in this section demonstrates OAuth client credentials only for an API whose current documentation requires that flow. Token URLs, request fields and credential placement must come from the selected product and account reference.


private async Task<string> GetAccessTokenAsync(
    CancellationToken cancellationToken)
{
    var formValues =
        new Dictionary<string, string>
        {
            { "client_id", _credentials.ClientId },
            { "client_secret", _credentials.ClientSecret },
            { "grant_type", "client_credentials" }
        };

    var content =
        new FormUrlEncodedContent(
            formValues);

    HttpResponseMessage response =
        await _httpClient.PostAsync(
            _credentials.TokenUrl,
            content,
            cancellationToken)
        .ConfigureAwait(false);

    response.EnsureSuccessStatusCode();

    string json =
        await response.Content
            .ReadAsStringAsync()
            .ConfigureAwait(false);

    var tokenResponse =
        JsonConvert.DeserializeObject<TokenResponse>(
            json);

    return tokenResponse.access_token;
}
                

5. Build a Request from the Selected API Contract

The sample uses a JSON array to illustrate how one or more tracking references might be passed. Field names and single-versus-bulk request behavior must match the selected API contract.


var requestObj =
    new TrackingBulkRequest
    {
        trackingReferences =
            new[] { cleanTrackingNumber }
    };

string json =
    JsonConvert.SerializeObject(
        requestObj);
                

6. Send the Required API Headers

The example header names are placeholders. Send only the credentials and authorization headers documented for the selected API; use Bearer tokens only when its authentication scheme specifies them.


using var request =
    new HttpRequestMessage(
        HttpMethod.Post,
        _credentials.ApiEndpoint)
    {
        Content =
            new StringContent(
                json,
                Encoding.UTF8,
                "application/json")
    };

request.Headers.Add(
    "X-Example-Access-Key",
    _credentials.AccessKey);

request.Headers.Add(
    "X-Example-API-Key",
    _credentials.ApiKey);

request.Headers.Authorization =
    new AuthenticationHeaderValue(
        "Bearer",
        accessToken);
                

7. Send the Tracking Request Through the Configured HttpClient

The integration uses the injected HttpClient and propagates the supplied CancellationToken to the network call.


HttpResponseMessage response =
    await _httpClient.SendAsync(
        request,
        cancellationToken)
    .ConfigureAwait(false);

string respJson =
    await response.Content
        .ReadAsStringAsync()
        .ConfigureAwait(false);
                

This keeps HTTP configuration outside the tracking logic while allowing the application to apply its normal networking and timeout policies.


8. Handle Unsuccessful Asendia Responses Explicitly

The client checks IsSuccessStatusCode. When Asendia returns an unsuccessful HTTP response, the integration logs the status code and response body and returns a stable error result.


if (!response.IsSuccessStatusCode)
{
    _logger.LogError(
        "Asendia API error: {StatusCode} - {Response}",
        response.StatusCode,
        respJson);

    return CreateErrorTrackingInfo(
        $"API error: {response.StatusCode}");
}
                

In production, response-body logging should be reviewed so credentials and unnecessary customer or shipment information are not written to logs.


9. Deserialize the Asendia Tracking Response

A successful response is deserialized into the carrier-specific TrackingBulkResponse model before application-level mapping occurs.


var bulkResponse =
    JsonConvert.DeserializeObject<TrackingBulkResponse>(
        respJson);

return MapToTrackingInfo(
    bulkResponse,
    cleanTrackingNumber);
                

This creates a clean boundary between the carrier's JSON contract and the application's normalized tracking model.


10. Distinguish Tracking Data from Not-Found Results

A tracking adapter should handle the success, no-match and error response shapes documented by the selected API. The field names in the DTO below are illustrative placeholders, not a universal Asendia response contract.


if (response.data != null &&
    response.data.Count > 0)
{
    var detail = response.data[0];

    return MapTrackingDetail(
        detail,
        trackingNumber);
}

if (response.data_not_found != null &&
    response.data_not_found.Count > 0)
{
    _logger.LogInformation(
        "Asendia tracking number not found: {TrackingNumber}",
        trackingNumber);

    return CreateNoTrackingDataInfo();
}

_logger.LogWarning(
    "Asendia response without data: {Message}",
    response.message);

return CreateNoTrackingDataInfo();
                

11. Find the Most Recent Event by EventTime

If a response contains timestamped events, use the timestamp field and ordering rules documented by that API to select the update to display.


EventDetail? latestEvent = null;

if (detail.events != null &&
    detail.events.Count > 0)
{
    latestEvent =
        detail.events
            .OrderByDescending(
                e => e.EventTime)
            .FirstOrDefault();
}
                

This is one of the most important source-specific details because the event collection order is not used as the definition of recency.


12. Build a Rich Display Status from the Latest Event

The current display value begins with the carrier-level Status. When an event is available, the implementation prefers the event's Label, falls back to Description, and appends a formatted timestamp and location.


string richDetail =
    detail.Status ?? "Unknown";

if (latestEvent != null)
{
    string eventLabel =
        latestEvent.Label
        ?? latestEvent.Description
        ?? string.Empty;

    string eventTime =
        latestEvent.EventTime ?? string.Empty;

    string location =
        latestEvent.LocationName ?? string.Empty;

    if (!string.IsNullOrWhiteSpace(eventLabel))
        richDetail = eventLabel;

    if (!string.IsNullOrWhiteSpace(eventTime))
    {
        if (DateHelper.TryParseDateTime(
            eventTime,
            out DateTime dt))
        {
            richDetail +=
                $" on {dt:dd MMM yyyy HH:mm}";
        }
        else
        {
            richDetail +=
                $" on {eventTime}";
        }
    }

    if (!string.IsNullOrWhiteSpace(location))
        richDetail += $" at {location}";
}
                

13. Normalize Asendia Statuses into Standard States

A sample mapping can convert provider-defined event codes or descriptions into application states. The values shown here are illustrative; use the actual codes, labels and precedence rules returned by the selected interface.

Application stateIllustrative event text (verify against the selected API)
DeliveredA documented delivery-complete event
In TransitA documented movement or out-for-delivery event
PendingA documented pre-advice or label-created event

14. Map Delivered, Transit and Pre-Shipment Wording

A small normalization function can map known provider values. Prefer documented event codes or exact values where available, and handle unknown values explicitly instead of relying on broad substring matches.


private string NormalizeStatus(
    string rawStatus)
{
    if (string.IsNullOrWhiteSpace(rawStatus))
        return "Pending";

    string lower =
        rawStatus.Trim().ToLowerInvariant();

    if (lower.Contains("delivered") ||
        lower.Contains("delivery successful") ||
        lower.Contains("successfully delivered"))
    {
        return "Delivered";
    }

    if (lower.Contains("in transit") ||
        lower.Contains("check-in asendia facility") ||
        lower.Contains("arrived at facility") ||
        lower.Contains("arrived at sorting") ||
        lower.Contains("arrived at depot") ||
        lower.Contains("departed") ||
        lower.Contains("processed at") ||
        lower.Contains("handed over") ||
        lower.Contains("on its way") ||
        lower.Contains("out for delivery") ||
        lower.Contains("delivery in progress"))
    {
        return "In Transit";
    }

    if (lower.Contains("electronic notification") ||
        lower.Contains("order data provided") ||
        lower.Contains("shipment information received") ||
        lower.Contains("label created") ||
        lower.Contains("pre-advice"))
    {
        return "Pending";
    }

    return "Pending";
}
                

15. Present Status Without Inventing Progress

Tracking events describe carrier-reported states; they do not necessarily define a percentage-complete value. Show a normalized status and its documented event time. Add a progress bar only when the chosen product has a reliable milestone model that can be mapped consistently.


16. Format the Latest Event Date

The most recent event drives the tracking timestamp when it contains a usable EventTime. The implementation uses DateHelper.TryParseDateTime and falls back to the raw value when parsing is unsuccessful.


string lastUpdate = "—";

if (latestEvent != null &&
    !string.IsNullOrWhiteSpace(
        latestEvent.EventTime))
{
    if (DateHelper.TryParseDateTime(
        latestEvent.EventTime,
        out DateTime dt))
    {
        lastUpdate =
            dt.ToString(
                "dd MMM yyyy, HH:mm");
    }
    else
    {
        lastUpdate =
            latestEvent.EventTime;
    }
}
else if (!string.IsNullOrWhiteSpace(
    detail.LastStatusDate))
{
    if (DateHelper.TryParseDateTime(
        detail.LastStatusDate,
        out DateTime dt))
    {
        lastUpdate =
            dt.ToString(
                "dd MMM yyyy, HH:mm");
    }
    else
    {
        lastUpdate =
            detail.LastStatusDate;
    }
}
                

17. Keep Event Time Separate from Estimated Delivery

The latest event time records when the carrier reported an update. It is not an estimated-delivery date. Populate an estimate only when the selected API explicitly supplies one, and keep the two values in separate fields.


18. Return a Stable TrackingInfo Model

Once the current event, status and date have been resolved, the client returns a TrackingInfo object. The carrier-specific detail is preserved in RawData.


return new TrackingInfo
{
    Status = normalizedStatus,
    DisplayStatus = richDetail,
    
    
    LastUpdate = lastUpdate,
    RawData = detail
};
                

19. Handle Asendia No-Tracking Data Explicitly

A client should return a clear no-tracking result when the documented response contains no matching events.


private TrackingInfo CreateNoTrackingDataInfo()
{
    return new TrackingInfo
    {
        Status = "No Tracking Data",
        DisplayStatus = "No Tracking Data",
        
        
        LastUpdate = "—"
    };
}
                

This is intentionally different from an integration exception. The API responded, but the application did not receive usable tracking data.


20. Return a Predictable Error Result

Unexpected failures and explicit API errors are converted into a stable Exception result.


private TrackingInfo CreateErrorTrackingInfo(
    string errorMessage)
{
    return new TrackingInfo
    {
        Status = "Exception",
        DisplayStatus = errorMessage,
        
        
        LastUpdate = errorMessage
    };
}
                

21. Keep Carrier DTOs Inside the Integration Boundary

A custom adapter can define DTOs for the exact API version in use. The names below are example application types and do not represent an official Asendia schema.


private class TrackingBulkRequest
{
    public string[] trackingReferences { get; set; }
}

private class TokenResponse
{
    public string access_token { get; set; }
    public int expires_in { get; set; }
}

private class TrackingBulkResponse
{
    public List<TrackingDetail> data { get; set; }
    public List<string> data_not_found { get; set; }
    public string message { get; set; }
}
                

22. Protect Asendia Credentials and Customer Information

A project-specific options object can hold endpoint and credential settings required by the selected interface. Keep secrets in secure configuration or a managed secret store, and do not assume every Asendia product uses the same fields.

The same rule applies to customer identifiers, carrier account information and environment-specific endpoint details. The article focuses on the integration design rather than exposing operational secrets.


23. Propagate Cancellation to Asendia Requests

Pass a CancellationToken through outgoing network calls so cancellation from the calling application can stop work that is no longer needed.


await GetAccessTokenAsync(
    cancellationToken);

await _httpClient.SendAsync(
    request,
    cancellationToken)
    .ConfigureAwait(false);
                

24. Use Asendia as One Carrier in a Multi-Carrier Architecture

Asendia should remain isolated as one carrier implementation while the application layer provides a consistent tracking workflow for UPS, DHL, DPD and Asendia.


ITrackingClient
      │
      ├── UPS Tracking Client
      ├── DHL Tracking Client
      ├── DPD Tracking Client
      └── Asendia Tracking Client
                

The individual carrier implementations can use different protocols, authentication flows and response models while the rest of the application works with a normalized tracking result.


25. Measure Authentication, API and Response Mapping Separately

A slow tracking screen can have several causes. Measure token acquisition, the Asendia API call, JSON deserialization, event sorting and status mapping independently rather than treating the whole operation as a single timing.


Documented authentication: measure separately
Asendia API request:  measure separately
JSON deserialization: measure separately
Event ordering:       measure separately
Status mapping:       measure separately
                

26. Be Deliberate About Tracking Caching

Whether to cache a token or tracking result depends on the selected API contract, token expiry, data freshness and carrier rules. Use the documented expiry and freshness policy; do not assume that caching is supported or required.

A future caching layer could be introduced according to tracking-freshness requirements, but that would be an architectural enhancement rather than a description of the supplied code.


27. Test Asendia Tracking at Multiple Levels

  • Test tracking-number trimming and trailing-comma removal.
  • Test the documented authentication success and failure paths.
  • Test JSON request creation and required request headers.
  • Test unsuccessful HTTP responses.
  • Test responses with populated data.
  • Test the documented no-match response and empty-result cases.
  • Test latest-event selection by EventTime.
  • Test status normalization for every known phrase and unknown values.
  • Test valid and invalid EventTime values.
  • Test the mapping from TrackingInfo into the application's common tracking model.

28. The Complete Asendia Tracking Flow

The sample implementation can be summarized as the following request lifecycle:


1. Receive tracking number
        ↓
2. Trim and normalize tracking number
        ↓
3. Obtain documented credentials or token, if required
        ↓
4. Build TrackingBulkRequest
        ↓
5. Serialize JSON request
        ↓
6. Create POST HttpRequestMessage
        ↓
7. Add the documented access and API key headers, if required
        ↓
8. Add documented authorization, if required
        ↓
9. Send request with CancellationToken
        ↓
10. Read response JSON
        ↓
11. Validate HTTP status
        ↓
12. Deserialize TrackingBulkResponse
        ↓
13. Handle event, empty and error results
        ↓
14. Find latest event by EventTime
        ↓
15. Build rich display status
        ↓
16. Normalize status
        ↓
17. Select a display status
        ↓
18. Format last update
        ↓
19. Return TrackingInfo
                

29. Asendia Tracking API Integration Checklist

  • Is the carrier integration isolated behind IAsendiaTrackingClient?
  • Are the credentials required by this API kept outside public source?
  • Is token acquisition handled according to the selected API documentation?
  • Is the tracking number normalized before the request?
  • Is the bulk JSON request built from trackingReferences?
  • Are the documented authentication credentials and headers sent correctly?
  • Are unsuccessful HTTP responses handled explicitly?
  • Are successful, empty and no-match responses handled according to the API contract?
  • Is the latest event determined by EventTime?
  • Are event labels, descriptions, locations and timestamps handled safely?
  • Are statuses normalized into application-level states?
  • Are no-data and exception results kept separate?
  • Is the current implementation documented accurately, without claiming caching that is not present?
  • Can Asendia coexist with UPS, DHL and DPD behind the same tracking workflow?

30. Conclusion

A reliable Asendia tracking integration starts by confirming the product-specific API contract, then handles its documented authentication, request fields, HTTP errors, response model and event semantics. Regional and account differences determine the implementation.

A sample adapter can isolate provider-specific authentication, request construction, event selection and status mapping behind an application-level tracking result. The exact flow must be taken from the selected Asendia product and account documentation.

That architecture allows Asendia to fit cleanly alongside UPS, DHL and DPD integrations without forcing the broader shipping application to understand every carrier's API contract.


31. About the Author

I'm Kshitij Mehta, a Senior .NET Developer and ASP.NET Core Consultant with experience developing enterprise software, shipping platforms, integrations and database-driven applications.

My work includes C#, ASP.NET Core, SQL Server, Dapper, ADO.NET, REST APIs, shipping software, carrier API integrations and enterprise application architecture.


For regional Asendia product and account scoping, see the Asendia API integration service and the ERP integration approach. The enterprise shipping platform case study shows how carrier tracking can fit into a broader operational workflow.