ContentstackClientOptions

View as Markdown

ContentstackClientOptions

ContentstackClientOptions holds every setting of a ContentstackClient in one object, in the Contentstack.Management.Core namespace.

When to Use This Class: Use this class to set what the individual-settings constructor of ContentstackClient does not take, such as retry limits, early access headers, and a custom retry condition. You can also use it to bind client settings through the .NET options pattern.

Conceptual Role: Acts as the configuration object of the client. Set its properties, then pass it to a ContentstackClient constructor.

Returns: ContentstackClientOptions. A settings object for one client.

Class-Level Properties

Connection and credentials.

NameTypeRequiredDefaultDescription
Authtokenstring?NonullAuthtoken sent as the authtoken header.
IsOAuthTokenboolNofalseSends Authtoken as authorization: Bearer instead.
HoststringNo"api.contentstack.io"Content Management API (CMA) host. Set it for another region.
PortintNo443Port of the CMA host.
VersionstringNo"v3"API version path segment.
EarlyAccessstring[]?NonullEarly access features, sent as one x-header-ea header.
TimeoutTimeSpanNo30 secondsTime to wait for each request attempt.
MaxResponseContentBufferSizelongNo1073741824Largest response body, in bytes (1 GB).
DisableLoggingboolNofalseTurns off the console log lines.

Proxy.

NameTypeRequiredDefaultDescription
ProxyHoststring?NonullHost of an HTTP proxy, without a scheme.
ProxyPortintNo-1Port of the proxy. -1 means no proxy.
ProxyCredentialsICredentials?NonullCredentials for the proxy.

Retries on HTTP error statuses.

NameTypeRequiredDefaultDescription
RetryOnErrorboolNotrueTurns every automatic retry on or off.
RetryLimitintNo5Most retries for statuses that RetryCondition selects.
RetryDelayTimeSpanNo300 millisecondsBase wait before a status retry.
RetryConditionFunc<HttpStatusCode, bool>?NonullPicks the statuses to retry. null means 429, 500, 502, 503, 504.
RetryOnHttpServerErrorboolNotrueRetries 500 to 504 responses.
RetryDelayOptionsRetryDelayOptions?NonullBase wait and a custom wait function for status retries.
RetryPolicyRetryPolicy?NonullReplaces the built-in retry logic.

Retries on network failures.

NameTypeRequiredDefaultDescription
RetryOnNetworkFailureboolNotrueRetries timeouts and other network failures.
RetryOnDnsFailureboolNotrueRetries failed host name lookups.
RetryOnSocketFailureboolNotrueRetries refused, reset, and unreachable connections.
MaxNetworkRetriesintNo3Most retries for network failures.
NetworkRetryDelayTimeSpanNo100 millisecondsBase wait before a network retry.
NetworkBackoffStrategyBackoffStrategyNoBackoffStrategy.ExponentialHow the network wait grows: Exponential or Fixed.

Known issue When the API keeps returning a 500 to 504 status, the client retries without a limit and with ever longer waits, so the call never returns. Set RetryOnHttpServerError to false and set RetryCondition to a function that leaves out 500 to 504, for example status => (int)status == 429, or set RetryOnError to false.

Known issue Code outside the SDK cannot create a RetryPolicy to assign to RetryPolicy, because the class has an internal abstract member. Use RetryCondition, RetryDelayOptions, and the limits above instead.

Class-Level Notes

The client reads most settings once.

  • The constructor applies Timeout, MaxResponseContentBufferSize, EarlyAccess, DisableLogging, the proxy, and the retry settings when it creates the client. A later change to these properties does not reach that client. Create a new client instead.
  • The client reads Authtoken, IsOAuthToken, Host, Port, and Version on every request. It also writes Authtoken and IsOAuthToken itself when you sign in, sign out, or complete an Open Authorization (OAuth) flow. Use one options object per client.

Host and region.

  • The client has no region setting. To reach another region, set Host to that region's CMA host, for example eu-api.contentstack.com. The Endpoint class looks up a region's hosts.
  • The client always uses https and builds the base URL from Host, Port, and Version. See the GetUri method.

How status retries work.

  • The SDK retries when RetryOnError is true and the status matches RetryCondition. When RetryCondition is null, the SDK matches the status against the default list 429, 500, 502, 503, 504.
  • For a status outside 500 to 504, such as 429, these retries stop after RetryLimit retries, so the default sends at most six requests.
  • A 500 to 504 status has no retry limit while RetryOnHttpServerError is true or RetryCondition selects it, and its wait follows the network formula below. See the Known issue above.
  • The wait before retry number n is the base wait times 2 to the power n, plus a random 0 to 100 milliseconds. The base wait is RetryDelayOptions.Base, or RetryDelay when RetryDelayOptions is null. With the defaults, the waits are about 600, 1200, 2400, 4800, and 9600 milliseconds.
  • RetryDelayOptions.CustomBackoff replaces that formula. The SDK calls it with the retry count and null for the exception, and waits for the TimeSpan it returns. A zero value retries at once, so it does not cancel the retry.
  • The SDK does not read the Retry-After header of a 429 response.
  • When the SDK stops retrying, it throws the last ContentstackErrorException.

How network retries work.

  • The SDK treats a timeout, a refused or reset connection, an unreachable host, and a failed host name lookup as network failures. It retries them up to MaxNetworkRetries times when RetryOnError, RetryOnNetworkFailure, and the matching RetryOnDnsFailure or RetryOnSocketFailure are true.

The wait before network retry number n is NetworkRetryDelay times 2 to the power n - 1 for Exponential. The wait is NetworkRetryDelay for Fixed. Both waits add a random 0 to 100 milliseconds.

  • When the SDK stops retrying, it throws the original exception, for example TaskCanceledException for a timeout or HttpRequestException for a failed connection. It does not wrap it in ContentstackErrorException.
  • Timeout applies to each attempt. A call that times out on every attempt takes up to four times Timeout, plus the waits.

Capability Matrix

CapabilitySupportedNotes / Alternative
Select a region by nameNoSet Host. Look up the host with Endpoint.
Honor the Retry-After headerNoSet RetryDelay or RetryDelayOptions.CustomBackoff to wait longer.
Log to a destination other than the consoleNoSet DisableLogging to true and log in your own code.
Change a setting on a client that existsNoCreate a new client with a new options object.

Method Index

ContentstackClientOptions has two methods. The client calls both itself, and you can call them to check the values it uses.

Method NameReturnsDescription
GetUriThe base URL of the CMA requests.Builds the base URL from the host, port, and version.
GetWebProxyThe proxy built from the proxy settings.Builds a WebProxy from the proxy settings.

Class-Level Snippet

This snippet creates a client for the EU region with a longer timeout, fewer retries, and a proxy, then fetches a stack.

using System;
using System.Net;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;

ContentstackClientOptions options = new ContentstackClientOptions()
{
    Authtoken = "<AUTHTOKEN>",
    Host = "eu-api.contentstack.com",
    Timeout = TimeSpan.FromSeconds(60),
    RetryLimit = 3,
    RetryDelay = TimeSpan.FromMilliseconds(500),
    RetryOnHttpServerError = false,
    RetryCondition = status => (int)status == 429,
    ProxyHost = "<PROXY_HOST>",
    ProxyPort = 8080,
    ProxyCredentials = new NetworkCredential("<PROXY_USERNAME>", "<PROXY_PASSWORD>")
};

ContentstackClient client = new ContentstackClient(options);

try
{
    ContentstackResponse response = client.Stack("<API_KEY>").Fetch();
    Console.WriteLine(response.OpenJsonObjectResponse().ToJsonString());
}
catch (ContentstackErrorException e)
{
    Console.WriteLine($"Request failed: {(int)e.StatusCode} {e.ErrorCode} {e.ErrorMessage}");
}

Methods

Each method of the ContentstackClientOptions class has its own section below, with its parameters, validation rules, behavior, and examples.

GetUri

GetUri builds the base URL that the client puts in front of every Content Management API (CMA) request path.

This method takes no parameters.

Returns: Uri. The base URL of the CMA requests.

Validation

  • Throws UriFormatException if Host is empty or is not a valid host name, because UriBuilder cannot build a URL from it.
  • Throws ArgumentOutOfRangeException if Port is lower than -1 or higher than 65535.

Behavior

  • Client-side only. GetUri sends no request.
  • Returns https://<Host>:<Port>/<Version>, for example https://api.contentstack.io/v3 with the defaults. The scheme is always https, even when Host starts with http://.
  • The client calls GetUri on every request, so a change to Host, Port, or Version reaches the next request.

Example

Basic usage: print the base URL for the EU region

using System;
using Contentstack.Management.Core;

ContentstackClientOptions options = new ContentstackClientOptions() { Host = "eu-api.contentstack.com" };

Uri baseUrl = options.GetUri();
Console.WriteLine(baseUrl);

GetWebProxy

GetWebProxy builds a WebProxy from ProxyHost, ProxyPort, and ProxyCredentials.

This method takes no parameters.

Returns: IWebProxy. The proxy built from the proxy settings.

Validation

  • Returns null when ProxyHost is empty or ProxyPort is -1. It does not throw.
  • The SDK does not check that the proxy host exists or answers. A wrong host fails at the first request.

Behavior

  • Client-side only. GetWebProxy sends no request.
  • Removes a leading http:// from ProxyHost, then creates a WebProxy for that host and ProxyPort.
  • Sets ProxyCredentials on the proxy when it has a value.
  • The client calls GetWebProxy once, when the constructor creates its HttpClient. A client that you create with your own HttpClient does not call it.

Example

Basic usage: check the proxy the client uses

using System;
using System.Net;
using Contentstack.Management.Core;

ContentstackClientOptions options = new ContentstackClientOptions()
{
    ProxyHost = "<PROXY_HOST>",
    ProxyPort = 8080,
    ProxyCredentials = new NetworkCredential("<PROXY_USERNAME>", "<PROXY_PASSWORD>")
};

IWebProxy? proxy = options.GetWebProxy();
Console.WriteLine(proxy == null ? "No proxy" : "Proxy configured");

Edge case: no proxy without a port

using System;
using System.Net;
using Contentstack.Management.Core;

// ProxyPort keeps its default of -1, so the SDK builds no proxy.
ContentstackClientOptions options = new ContentstackClientOptions() { ProxyHost = "<PROXY_HOST>" };

IWebProxy? proxy = options.GetWebProxy();
Console.WriteLine(proxy == null);