ContentstackClient
ContentstackClient
ContentstackClient is the entry point of the .NET Management SDK. It holds the connection settings and the credentials, and every other object in the SDK starts from it.
When to Use This Class: Create one client per set of credentials. Use the client to sign in, reach a stack or an organization, and send Content Management API (CMA) requests.
Conceptual Role: Acts as the HTTP client for the CMA. It stores the authtoken, runs the retry pipeline, and passes itself to the Stack, Organization, and User objects it creates.
Returns: ContentstackClient. A new client.
Instance State
The credentials the client holds decide which methods you can call:
- A client without an authtoken can call Login, OAuth, and the password methods of client.User(), for example ForgotPassword.
A client with an authtoken, from the constructor, from Login, or from an Open Authorization (OAuth) token exchange, can call GetUser and the Organization methods, for example GetOrganizations.
- A Stack created with a management token works on a client without an authtoken, for example client.Stack("<API_KEY>", "<MANAGEMENT_TOKEN>").
Calling a method in the wrong state throws InvalidOperationException before any request leaves the SDK. Login on a client that already has an authtoken throws, and GetUser on a client without one throws. The Method Index below lists every method.
Class-Level Notes
Authentication.
- The client sends its authtoken as the authtoken header on every request. Set it in the constructor, or call Login to get one.
- A management token belongs to one stack. Pass it to Stack, and the requests from that Stack send it as the authorization header instead of the authtoken.
- An OAuth access token replaces the authtoken. After an OAuth token exchange, the client sends authorization: Bearer <ACCESS_TOKEN>. See the OAuthHandler class page.
The client writes credentials into the options object.
- The client keeps the ContentstackClientOptions object you pass and writes into it. Login stores the new authtoken in Authtoken, Logout clears it, and an OAuth token exchange sets Authtoken and IsOAuthToken.
- Two clients that share one options object therefore share one authtoken. Create an options object for each client.
Errors.
- A method that sends a request throws ContentstackErrorException when the API returns an error status. Read StatusCode, ErrorCode, ErrorMessage, and Errors on it. See the ContentstackErrorException class page.
- A method that returns without throwing returns a ContentstackResponse with a success status. Read its body with OpenJsonObjectResponse() or OpenTResponse<T>().
Rate Limiting & Retry.
- The client retries a 429 up to RetryLimit times. A 500 to 504 status that keeps failing has no retry limit, as the Known issue on the ContentstackClientOptions page describes.
Additional Resource Refer to the ContentstackClientOptions class page to configure retries, the timeout, the host, and a proxy.
Async methods.
- Each ...Async method runs its client-side checks when you call it, before it returns a task. An API rejection surfaces when you await the task.
- await every async method. Reading .Result or calling .Wait() wraps an API rejection in AggregateException, so a catch (ContentstackErrorException) block does not catch it.
Capability Matrix
| Capability | Supported | Notes / Alternative |
|---|---|---|
| Select a region by name | No | Set Host to the region's CMA host, for example eu-api.contentstack.com. The Endpoint class looks up a region's hosts. |
| Sign in as a second user on the same client | No | Login throws while the client holds an authtoken. Call Logout first, or create a second client. |
| Refresh an OAuth token on a sync call | No | Only async methods refresh an OAuth token that is about to expire. See the OAuthHandler class page. |
| Change the host, timeout, or proxy after construction | No | The constructor applies these settings to the HTTP client once. Create a new client. |
Class-Level Properties
| Property | Type | Access | Default | Description |
|---|---|---|---|---|
| SerializerOptions | JsonSerializerOptions | Read/write | Case-insensitive names, null values skipped, the SDK's converters | Options the SDK uses to write request bodies and read responses. |
| LogManager | LogManager? | Read/write | A console logger, or an empty logger when DisableLogging is true | Logger for retry and error lines. |
Method Index
The groups below follow what you want to do. Every method is available on every client.
Create a client. Available through new ContentstackClient(...).
| Method Name | Returns | Description |
|---|---|---|
| ContentstackClient | A new client. | Creates a client from options or individual settings. |
Sign in and out with an authtoken. Available on every client. Login and LoginAsync need a client without an authtoken.
| Method Name | Returns | Description |
|---|---|---|
| Login | The API response with the signed-in user and authtoken. | Signs in with an email and password. |
| LoginAsync | The API response with the signed-in user and authtoken. | Signs in with an email and password asynchronously. |
| Logout | The logout result. | Signs out and ends the authtoken session. |
| LogoutAsync | The logout result. | Signs out asynchronously. |
Read the signed-in user. Available on a client with an authtoken.
| Method Name | Returns | Description |
|---|---|---|
| GetUser | The API response with the signed-in user. | Retrieves the account behind the authtoken. |
| GetUserAsync | The API response with the signed-in user. | Retrieves the account behind the authtoken asynchronously. |
Reach resources. Available on every client. Each method returns an object and sends no request.
| Method Name | Returns | Description |
|---|---|---|
| Stack | A new stack object. | Reaches one stack, or the stack collection. |
| Organization | A new organization object. | Reaches one organization, or every organization. |
| User | A new user object. | Reaches the password reset requests. |
Authenticate with OAuth. Available on every client.
| Method Name | Returns | Description |
|---|---|---|
| OAuth | A new OAuth handler. | Starts an OAuth 2.0 flow for an app. |
| GetOAuthTokens | The stored tokens for the client ID. | Reads the OAuth tokens stored for an app. |
| HasOAuthTokens | True when the client holds tokens for the client ID. | Checks for stored OAuth tokens. |
| HasValidOAuthTokens | True when the client holds valid tokens for the client ID. | Checks for an unexpired OAuth access token. |
| ClearOAuthTokens | This method returns nothing. | Removes stored OAuth tokens. |
Release the client. Available on every client.
| Method Name | Returns | Description |
|---|---|---|
| Dispose | This method returns nothing. | Releases the HTTP client and the request pipeline. |
Class-Level Snippet
This snippet signs in with an email and password, lists the stacks of an organization, and signs out.
using System;
using System.Net;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
ContentstackClient client = new ContentstackClient();
try
{
client.Login(new NetworkCredential("<EMAIL>", "<PASSWORD>"));
ContentstackResponse stacks = client.Organization("<ORGANIZATION_UID>").GetStacks();
Console.WriteLine(stacks.OpenJsonObjectResponse().ToJsonString());
client.Logout();
}
catch (ContentstackErrorException e)
{
Console.WriteLine($"Request failed: {(int)e.StatusCode} {e.ErrorCode} {e.ErrorMessage}");
}Methods
Each method of the ContentstackClient class has its own section below, with its parameters, validation rules, behavior, and examples.
ClearOAuthTokens
ClearOAuthTokens removes stored Open Authorization (OAuth) tokens from this client and stops the client from sending an OAuth access token.
| Name | Type | Description |
|---|---|---|
| clientId | string? | Client ID whose tokens to remove. Removes all when null. |
Returns: void. This method returns nothing.
Validation
- There is no client-side validation. A clientId with no stored tokens raises no error.
Behavior
- Client-side only. ClearOAuthTokens sends no request, so the API does not revoke the tokens. Call the Logout method of OAuthHandler to revoke the app authorization as well.
- With clientId, it removes the tokens of that app. With null or an empty string, it removes the tokens of every app.
- When the client sends an OAuth access token, ClearOAuthTokens also clears the client's Authtoken and sets IsOAuthToken to false. It does so even when clientId names a different app than the one whose token the client sends.
- After the call, the client sends no credentials until you set an authtoken, call Login, or complete a new OAuth flow.
Example
Basic usage: forget one app's tokens
using System;
using Contentstack.Management.Core;
ContentstackClient client = new ContentstackClient();
client.ClearOAuthTokens("<CLIENT_ID>");
Console.WriteLine(client.HasOAuthTokens("<CLIENT_ID>"));All parameters: forget the tokens of every app
using System;
using Contentstack.Management.Core;
ContentstackClient client = new ContentstackClient();
client.ClearOAuthTokens(null);
Console.WriteLine("Every stored OAuth token is gone");ContentstackClient
ContentstackClient creates a client for the Content Management API from an options object or from individual settings.
| Name | Type | Description |
|---|---|---|
| contentstackOptions (required) | ContentstackClientOptions | Every client setting in one object. |
| contentstackOptions (required) | IOptions<ContentstackClientOptions> | Settings from the .NET options pattern. |
| httpClient (required) | HttpClient | Your own HTTP client for every request. |
| authtoken | string? | Authtoken sent with every request. |
| host | string | Content Management API (CMA) host, without a path. |
| port | int | Port of the CMA host. |
| version | string | API version path segment. |
| disableLogging | bool | Turns off the console log lines. |
| maxResponseContentBufferSize | long | Largest response body, in bytes (1 GB). |
| timeout | int | Request timeout, in seconds. |
| retryOnError | bool | Turns automatic retries on or off. |
| proxyHost | string? | Host of an HTTP proxy. |
| proxyPort | int | Port of the HTTP proxy. -1 means no proxy. |
| proxyCredentials | ICredentials? | Credentials for the proxy. |
Returns: ContentstackClient. A new client.
Overloads
- ContentstackClient(ContentstackClientOptions contentstackOptions)
- ContentstackClient(IOptions<ContentstackClientOptions> contentstackOptions)
- ContentstackClient(HttpClient httpClient, ContentstackClientOptions contentstackOptions)
- ContentstackClient(string? authtoken, string host, int port, string version, bool disableLogging, long maxResponseContentBufferSize, int timeout, bool retryOnError, string? proxyHost, int proxyPort, ICredentials? proxyCredentials)
Validation
- The constructors do not validate the authtoken, the host, or any other setting. A missing or wrong value fails at the first request, with ContentstackErrorException or a network exception.
- Throws ArgumentNullException if httpClient is null, because the SDK sends every request through it.
- Throws InvalidOperationException if httpClient has already sent a request, because the constructor sets its Timeout, and HttpClient allows that only before its first request. Pass a new HttpClient.
- Throws NullReferenceException if contentstackOptions is null, or if the Value of the IOptions<ContentstackClientOptions> object is null.
Behavior
- The constructor that takes individual settings builds a ContentstackClientOptions object from them. Use the options constructor for the settings it does not take, such as EarlyAccess, RetryLimit, and RetryDelay. See the ContentstackClientOptions class page for each setting and its default.
- The constructor applies Timeout and MaxResponseContentBufferSize to the HTTP client and adds the X-User-Agent header, plus x-header-ea when EarlyAccess has values. These settings stay fixed for the life of the client.
- Without httpClient, the constructor creates an HttpClient that uses the proxy from ContentstackClientOptions.GetWebProxy().
- With httpClient, the SDK uses your client as given and ignores ProxyHost, ProxyPort, and ProxyCredentials. Configure a proxy on your own HttpClientHandler instead. Dispose disposes the HttpClient you pass.
- The client keeps a reference to the ContentstackClientOptions object and writes the authtoken into it when you sign in or out.
- timeout in the settings constructor is a number of seconds. The Timeout property of ContentstackClientOptions is a TimeSpan.
Example
Basic usage: create a client with an authtoken
using System;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
ContentstackClient client = new ContentstackClient("<AUTHTOKEN>");
try
{
ContentstackResponse response = client.GetUser();
Console.WriteLine(response.OpenJsonObjectResponse().ToJsonString());
}
catch (ContentstackErrorException e)
{
// Thrown when the API rejects the request
Console.WriteLine($"Request failed: {(int)e.StatusCode} {e.ErrorCode} {e.ErrorMessage}");
}All parameters: every individual setting
using System;
using System.Net;
using Contentstack.Management.Core;
ContentstackClient client = new ContentstackClient(
authtoken: "<AUTHTOKEN>",
host: "eu-api.contentstack.com",
port: 443,
version: "v3",
disableLogging: true,
maxResponseContentBufferSize: 104857600,
timeout: 60,
retryOnError: true,
proxyHost: "<PROXY_HOST>",
proxyPort: 8080,
proxyCredentials: new NetworkCredential("<PROXY_USERNAME>", "<PROXY_PASSWORD>"));
Console.WriteLine("Client created");Options object: settings the individual-settings constructor does not take
using System;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
ContentstackClientOptions options = new ContentstackClientOptions()
{
Authtoken = "<AUTHTOKEN>",
Host = "eu-api.contentstack.com",
RetryLimit = 3,
RetryDelay = TimeSpan.FromMilliseconds(500),
EarlyAccess = new string[] { "<EARLY_ACCESS_FEATURE>" }
};
ContentstackClient client = new ContentstackClient(options);
try
{
ContentstackResponse response = client.Stack("<API_KEY>").Fetch();
Console.WriteLine(response.OpenJsonObjectResponse().ToJsonString());
}
catch (ContentstackErrorException e)
{
Console.WriteLine(e.ErrorMessage);
}Dependency injection: the IOptions constructor
using System;
using Contentstack.Management.Core;
using Microsoft.Extensions.Options;
ContentstackClientOptions options = new ContentstackClientOptions() { Authtoken = "<AUTHTOKEN>" };
ContentstackClient client = new ContentstackClient(new OptionsWrapper<ContentstackClientOptions>(options));
Console.WriteLine("Client created");Edge case: pass your own HttpClient with a proxy
using System;
using System.Net;
using System.Net.Http;
using Contentstack.Management.Core;
// The SDK ignores ProxyHost when you pass an HttpClient, so set the proxy on the handler.
HttpClientHandler handler = new HttpClientHandler()
{
Proxy = new WebProxy("<PROXY_HOST>", 8080)
};
// Pass a new HttpClient. One that has already sent a request throws InvalidOperationException.
HttpClient httpClient = new HttpClient(handler);
ContentstackClient client = new ContentstackClient(httpClient, new ContentstackClientOptions() { Authtoken = "<AUTHTOKEN>" });
Console.WriteLine("Client created");Dispose
Dispose releases the HTTP client and the request pipeline of this client.
This method takes no parameters.
Returns: void. This method returns nothing.
Validation
- There is no client-side validation. A second call does nothing.
- After Dispose, every method that sends a request throws ObjectDisposedException. A sync method throws it when you call it, and an async method throws it when you await the task.
Behavior
- Client-side only. Dispose sends no request and does not sign out. Call Logout first to end an authtoken session.
- Disposes the HttpClient the client sends requests through, including one you passed to the constructor. Do not reuse that HttpClient afterward.
- ContentstackClient implements IDisposable, so a using declaration calls Dispose for you.
Example
Basic usage: dispose the client with a using declaration
using System;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
using ContentstackClient client = new ContentstackClient("<AUTHTOKEN>");
try
{
ContentstackResponse response = client.GetUser();
Console.WriteLine(response.OpenJsonObjectResponse().ToJsonString());
}
catch (ContentstackErrorException e)
{
// Thrown when the API rejects the request
Console.WriteLine($"Request failed: {(int)e.StatusCode} {e.ErrorCode} {e.ErrorMessage}");
}Edge case: a request after Dispose
using System;
using Contentstack.Management.Core;
ContentstackClient client = new ContentstackClient("<AUTHTOKEN>");
client.Dispose();
try
{
client.GetUser();
}
catch (ObjectDisposedException e)
{
// Fires before any request, because the HTTP client is released
Console.WriteLine(e.Message);
}GetOAuthTokens
GetOAuthTokens returns the Open Authorization (OAuth) tokens that this client stores for an app's client ID.
| Name | Type | Description |
|---|---|---|
| clientId (required) | string | Client ID of the OAuth app. |
Returns: OAuthTokens. The stored tokens for the client ID.
Validation
- Throws ArgumentException (parameter clientId) if clientId is null or empty, because the client stores tokens by client ID.
- Returns null when the client stores no tokens for clientId. It does not throw.
Behavior
- Client-side only. GetOAuthTokens reads the in-memory token store of this client and sends no request.
- Returns the stored object itself, not a copy. A change to its properties changes the stored tokens.
- The client fills the store when an OAuthHandler exchanges a code or refreshes a token. See the OAuthTokens class page for the properties.
Example
Basic usage: read the access token after an OAuth sign-in
using System;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
using Contentstack.Management.Core.Models;
ContentstackClient client = new ContentstackClient();
OAuthHandler oauth = client.OAuth(new OAuthOptions() { AppId = "<APP_ID>", ClientId = "<CLIENT_ID>", RedirectUri = "<REDIRECT_URI>" });
try
{
string authorizationUrl = await oauth.AuthorizeAsync();
Console.WriteLine($"Open {authorizationUrl}, then paste the code from the redirect.");
await oauth.ExchangeCodeForTokenAsync(Console.ReadLine() ?? "");
OAuthTokens tokens = client.GetOAuthTokens("<CLIENT_ID>");
Console.WriteLine($"Access token expires at {tokens?.ExpiresAt:u}");
}
catch (OAuthException e)
{
// Thrown when the token exchange fails
Console.WriteLine($"OAuth failed: {e.Message}");
}Edge case: no tokens stored
using System;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Models;
ContentstackClient client = new ContentstackClient();
OAuthTokens tokens = client.GetOAuthTokens("<CLIENT_ID>");
Console.WriteLine(tokens == null ? "No tokens stored" : tokens.AccessToken);GetUser
GetUser retrieves the details of the account that the client's authtoken belongs to.
| Name | Type | Description |
|---|---|---|
| collection | ParameterCollection? | Query parameters added to the request. |
Returns: ContentstackResponse. The API response with the signed-in user.
Validation
- Throws InvalidOperationException if the client has no authtoken, because the Get user request reads the account behind an authtoken. A management token does not count, since it belongs to a stack, not a user.
- collection set to null sends no query parameters.
- Throws ContentstackErrorException when the API rejects the request, for example for an expired authtoken.
Additional Resource Refer to Content Management API Errors for the full error code list.
Behavior
- GetUser sends one GET /user request, the Get user request of the Content Management API (CMA), with every entry of collection as a query parameter.
- Returns the raw API response. The CMA describes the response as the account details, including the stacks the user owns and the stacks shared with the user.
- An Open Authorization (OAuth) access token counts as the client's authtoken, so GetUser works after an OAuth token exchange.
Example
Basic usage: read the signed-in user
using System;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
ContentstackClient client = new ContentstackClient("<AUTHTOKEN>");
try
{
ContentstackResponse response = client.GetUser();
Console.WriteLine(response.OpenJsonObjectResponse().ToJsonString());
}
catch (ContentstackErrorException e)
{
// Thrown when the API rejects the request
Console.WriteLine($"Request failed: {(int)e.StatusCode} {e.ErrorCode} {e.ErrorMessage}");
}All parameters: add a query parameter
using System;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
using Contentstack.Management.Core.Queryable;
ContentstackClient client = new ContentstackClient("<AUTHTOKEN>");
ParameterCollection collection = new ParameterCollection();
collection.Add("<PARAMETER_NAME>", "<PARAMETER_VALUE>");
try
{
ContentstackResponse response = client.GetUser(collection);
Console.WriteLine(response.OpenJsonObjectResponse().ToJsonString());
}
catch (ContentstackErrorException e)
{
Console.WriteLine(e.ErrorMessage);
}Edge case: a client without an authtoken
using System;
using Contentstack.Management.Core;
ContentstackClient client = new ContentstackClient();
try
{
client.GetUser();
}
catch (InvalidOperationException e)
{
// Fires before any request, because the client holds no authtoken
Console.WriteLine(e.Message);
}GetUserAsync
GetUserAsync retrieves the details of the account that the client's authtoken belongs to, without blocking the calling thread.
| Name | Type | Description |
|---|---|---|
| collection | ParameterCollection? | Query parameters added to the request. |
Returns: Task<ContentstackResponse>. The API response with the signed-in user.
Validation
- Throws InvalidOperationException if the client has no authtoken. The SDK throws it when you call GetUserAsync, before it returns a task.
- Throws ContentstackErrorException when you await the task and the API rejects the request.
Additional Resource Refer to Content Management API Errors for the full error code list.
Behavior
- Otherwise behaves like GetUser.
Example
Basic usage: read the signed-in user
using System;
using System.Threading.Tasks;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
ContentstackClient client = new ContentstackClient("<AUTHTOKEN>");
try
{
ContentstackResponse response = await client.GetUserAsync();
Console.WriteLine(response.OpenJsonObjectResponse().ToJsonString());
}
catch (ContentstackErrorException e)
{
// Thrown when the API rejects the request
Console.WriteLine($"Request failed: {(int)e.StatusCode} {e.ErrorCode} {e.ErrorMessage}");
}All parameters: add a query parameter
using System;
using System.Threading.Tasks;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
using Contentstack.Management.Core.Queryable;
ContentstackClient client = new ContentstackClient("<AUTHTOKEN>");
ParameterCollection collection = new ParameterCollection();
collection.Add("<PARAMETER_NAME>", "<PARAMETER_VALUE>");
try
{
ContentstackResponse response = await client.GetUserAsync(collection);
Console.WriteLine(response.OpenJsonObjectResponse().ToJsonString());
}
catch (ContentstackErrorException e)
{
Console.WriteLine(e.ErrorMessage);
}HasOAuthTokens
HasOAuthTokens checks whether this client stores Open Authorization (OAuth) tokens for an app's client ID, whether or not they have expired.
| Name | Type | Description |
|---|---|---|
| clientId (required) | string | Client ID of the OAuth app. |
Returns: bool. True when the client holds tokens for the client ID.
Validation
- There is no client-side validation. HasOAuthTokens returns false for a null or empty clientId. It does not throw.
Behavior
- Client-side only. HasOAuthTokens reads the in-memory token store of this client and sends no request.
- Returns true for expired tokens too. Call HasValidOAuthTokens to check for a usable access token.
Example
Basic usage: check for stored tokens
using System;
using Contentstack.Management.Core;
ContentstackClient client = new ContentstackClient();
bool stored = client.HasOAuthTokens("<CLIENT_ID>");
Console.WriteLine(stored ? "Tokens stored" : "Sign in with OAuth first");HasValidOAuthTokens
HasValidOAuthTokens checks whether this client stores an unexpired Open Authorization (OAuth) access token for an app's client ID.
| Name | Type | Description |
|---|---|---|
| clientId (required) | string | Client ID of the OAuth app. |
Returns: bool. True when the client holds valid tokens for the client ID.
Validation
- There is no client-side validation. HasValidOAuthTokens returns false for a null or empty clientId. It does not throw.
Behavior
- Client-side only. HasValidOAuthTokens reads the in-memory token store of this client and sends no request.
- Returns true when the stored AccessToken is not empty and ExpiresAt is later than the current UTC time. This is the IsValid property of OAuthTokens.
- The SDK sets ExpiresAt 60 seconds before the expiry time the API returns, so the check turns false slightly early.
Example
Basic usage: refresh when the access token has expired
using System;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
using Contentstack.Management.Core.Models;
ContentstackClient client = new ContentstackClient();
OAuthHandler oauth = client.OAuth(new OAuthOptions() { AppId = "<APP_ID>", ClientId = "<CLIENT_ID>", RedirectUri = "<REDIRECT_URI>" });
try
{
if (client.HasOAuthTokens("<CLIENT_ID>") && !client.HasValidOAuthTokens("<CLIENT_ID>"))
{
await oauth.RefreshTokenAsync();
}
Console.WriteLine(client.HasValidOAuthTokens("<CLIENT_ID>"));
}
catch (OAuthException e)
{
// Thrown when the refresh request fails
Console.WriteLine($"OAuth failed: {e.Message}");
}Login
Login signs in to a Contentstack account with an email and password, and stores the authtoken from the response on the client.
| Name | Type | Description |
|---|---|---|
| credentials (required) | ICredentials | Email and password, as a NetworkCredential. |
| token | string? | Two-factor authentication (2FA) code from an authenticator app. |
| mfaSecret | string? | Base32 2FA secret. The SDK generates the code from it. |
Returns: ContentstackResponse. The API response with the signed-in user and authtoken.
Validation
- Throws InvalidOperationException if the client already has an authtoken, from the constructor, an earlier Login, or an Open Authorization (OAuth) token exchange. One client holds one session, so call Logout first or create a new client.
- Throws ArgumentNullException if credentials is null, because the request body needs an email and password.
- Throws ArgumentException if mfaSecret is not a valid Base32 string and token is empty, because the SDK cannot generate a code from it.
- Throws NullReferenceException if credentials is an ICredentials type other than NetworkCredential, because the SDK reads UserName and Password from a NetworkCredential.
- Throws ContentstackErrorException when the API rejects the request, for example for a wrong password or a missing 2FA code.
Additional Resource Refer to Content Management API Errors for the full error code list.
Behavior
- Login sends one POST /user-session request, the Log in to your account request of the Content Management API (CMA), with the body {"user": {"email": ..., "password": ..., "tfa_token": ...}}.
- On a success response, the SDK reads user.authtoken and stores it in the client's Authtoken option. Every later request from this client sends it as the authtoken header.
- The 2FA code comes from one of two places:
- When token has a value, the SDK sends it as tfa_token and ignores mfaSecret.
- When token is empty and mfaSecret has a value, the SDK generates a time-based one-time password (TOTP) from the secret with the current clock and sends it.
- Without token and mfaSecret, the request carries no tfa_token. An account with 2FA turned on then fails to sign in.
- Returns the raw API response. The user details, including authtoken, sit under the user key.
Additional Resource Refer to TOTP Support for .NET Management SDK to set up two-factor authentication.
Example
Basic usage: sign in with an email and password
using System;
using System.Net;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
ContentstackClient client = new ContentstackClient();
try
{
ContentstackResponse response = client.Login(new NetworkCredential("<EMAIL>", "<PASSWORD>"));
Console.WriteLine(response.OpenJsonObjectResponse()["user"]?["email"]);
}
catch (ContentstackErrorException e)
{
// Thrown when the API rejects the request
Console.WriteLine($"Request failed: {(int)e.StatusCode} {e.ErrorCode} {e.ErrorMessage}");
}All parameters: sign in with a 2FA code from an authenticator app
using System;
using System.Net;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
ContentstackClient client = new ContentstackClient();
try
{
ContentstackResponse response = client.Login(new NetworkCredential("<EMAIL>", "<PASSWORD>"), token: "<TOTP_TOKEN>", mfaSecret: null);
Console.WriteLine(response.OpenJsonObjectResponse()["user"]?["uid"]);
}
catch (ContentstackErrorException e)
{
Console.WriteLine(e.ErrorMessage);
}All parameters: let the SDK generate the 2FA code from the secret
using System;
using System.Net;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
ContentstackClient client = new ContentstackClient();
try
{
ContentstackResponse response = client.Login(new NetworkCredential("<EMAIL>", "<PASSWORD>"), mfaSecret: "<MFA_SECRET>");
Console.WriteLine(response.OpenJsonObjectResponse()["user"]?["uid"]);
}
catch (ContentstackErrorException e)
{
Console.WriteLine(e.ErrorMessage);
}Edge case: a client that already has an authtoken
using System;
using System.Net;
using Contentstack.Management.Core;
ContentstackClient client = new ContentstackClient("<AUTHTOKEN>");
try
{
client.Login(new NetworkCredential("<EMAIL>", "<PASSWORD>"));
}
catch (InvalidOperationException e)
{
// Fires before any request, because the client already holds an authtoken
Console.WriteLine(e.Message);
}LoginAsync
LoginAsync signs in to a Contentstack account with an email and password without blocking the calling thread, and stores the authtoken from the response on the client.
| Name | Type | Description |
|---|---|---|
| credentials (required) | ICredentials | Email and password, as a NetworkCredential. |
| token | string? | Two-factor authentication (2FA) code from an authenticator app. |
| mfaSecret | string? | Base32 2FA secret. The SDK generates the code from it. |
Returns: Task<ContentstackResponse>. The API response with the signed-in user and authtoken.
Validation
- Throws InvalidOperationException if the client already has an authtoken. Call LogoutAsync first or create a new client.
- Throws ArgumentNullException if credentials is null, and ArgumentException if mfaSecret is not valid Base32 while token is empty.
- The SDK throws the exceptions above when you call LoginAsync, before it returns a task.
- Throws ContentstackErrorException when you await the task and the API rejects the request.
Additional Resource Refer to Content Management API Errors for the full error code list.
Behavior
- Otherwise behaves like Login.
Example
Basic usage: sign in with an email and password
using System;
using System.Net;
using System.Threading.Tasks;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
ContentstackClient client = new ContentstackClient();
try
{
ContentstackResponse response = await client.LoginAsync(new NetworkCredential("<EMAIL>", "<PASSWORD>"));
Console.WriteLine(response.OpenJsonObjectResponse()["user"]?["email"]);
}
catch (ContentstackErrorException e)
{
// Thrown when the API rejects the request
Console.WriteLine($"Request failed: {(int)e.StatusCode} {e.ErrorCode} {e.ErrorMessage}");
}All parameters: sign in with a 2FA code
using System;
using System.Net;
using System.Threading.Tasks;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
ContentstackClient client = new ContentstackClient();
try
{
ContentstackResponse response = await client.LoginAsync(new NetworkCredential("<EMAIL>", "<PASSWORD>"), token: "<TOTP_TOKEN>", mfaSecret: null);
Console.WriteLine(response.OpenJsonObjectResponse()["user"]?["uid"]);
}
catch (ContentstackErrorException e)
{
Console.WriteLine(e.ErrorMessage);
}All parameters: let the SDK generate the 2FA code from the secret
using System;
using System.Net;
using System.Threading.Tasks;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
ContentstackClient client = new ContentstackClient();
try
{
ContentstackResponse response = await client.LoginAsync(new NetworkCredential("<EMAIL>", "<PASSWORD>"), mfaSecret: "<MFA_SECRET>");
Console.WriteLine(response.OpenJsonObjectResponse()["user"]?["uid"]);
}
catch (ContentstackErrorException e)
{
Console.WriteLine(e.ErrorMessage);
}Logout
Logout signs out of a Contentstack account and ends the session of an authtoken.
| Name | Type | Description |
|---|---|---|
| authtoken | string? | Authtoken to sign out. Uses the client's authtoken when null. |
Returns: ContentstackResponse. The logout result.
Validation
- Throws ArgumentNullException if authtoken is null or blank and the client has no authtoken, because the request needs a token to sign out.
- The SDK does not check that the token is valid. An unknown or expired token reaches the API.
- Throws ContentstackErrorException when the API rejects the request.
Additional Resource Refer to Content Management API Errors for the full error code list.
Behavior
- Logout sends one DELETE /user-session request, the Log out of your account request of the Content Management API (CMA), with the token in the authtoken header.
- After a success response, the SDK clears the client's authtoken only when it matches the token sent. Signing out another token leaves the client's own session in place.
- After Logout clears the authtoken of the client, you can call Login again on the same client.
- Logout ends an authtoken session only. To end an Open Authorization (OAuth) session, call the Logout method of OAuthHandler.
Example
Basic usage: sign out the client's session
using System;
using System.Net;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
ContentstackClient client = new ContentstackClient();
try
{
client.Login(new NetworkCredential("<EMAIL>", "<PASSWORD>"));
ContentstackResponse response = client.Logout();
Console.WriteLine(response.OpenJsonObjectResponse().ToJsonString());
}
catch (ContentstackErrorException e)
{
// Thrown when the API rejects the request
Console.WriteLine($"Request failed: {(int)e.StatusCode} {e.ErrorCode} {e.ErrorMessage}");
}All parameters: sign out a specific authtoken
using System;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
ContentstackClient client = new ContentstackClient();
try
{
ContentstackResponse response = client.Logout("<AUTHTOKEN>");
Console.WriteLine(response.OpenJsonObjectResponse().ToJsonString());
}
catch (ContentstackErrorException e)
{
Console.WriteLine(e.ErrorMessage);
}Edge case: no token to sign out
using System;
using Contentstack.Management.Core;
ContentstackClient client = new ContentstackClient();
try
{
client.Logout();
}
catch (ArgumentNullException e)
{
// Fires before any request, because neither the argument nor the client holds an authtoken
Console.WriteLine(e.ParamName);
}LogoutAsync
LogoutAsync signs out of a Contentstack account and ends the session of an authtoken, without blocking the calling thread.
| Name | Type | Description |
|---|---|---|
| authtoken | string? | Authtoken to sign out. Uses the client's authtoken when null. |
Returns: Task<ContentstackResponse>. The logout result.
Validation
- Throws ArgumentNullException if authtoken is null or blank and the client has no authtoken. The SDK throws it when you call LogoutAsync, before it returns a task.
- Throws ContentstackErrorException when you await the task and the API rejects the request.
Additional Resource Refer to Content Management API Errors for the full error code list.
Behavior
- Otherwise behaves like Logout.
Example
Basic usage: sign out the client's session
using System;
using System.Net;
using System.Threading.Tasks;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
ContentstackClient client = new ContentstackClient();
try
{
await client.LoginAsync(new NetworkCredential("<EMAIL>", "<PASSWORD>"));
ContentstackResponse response = await client.LogoutAsync();
Console.WriteLine(response.OpenJsonObjectResponse().ToJsonString());
}
catch (ContentstackErrorException e)
{
// Thrown when the API rejects the request
Console.WriteLine($"Request failed: {(int)e.StatusCode} {e.ErrorCode} {e.ErrorMessage}");
}All parameters: sign out a specific authtoken
using System;
using System.Threading.Tasks;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
ContentstackClient client = new ContentstackClient();
try
{
ContentstackResponse response = await client.LogoutAsync("<AUTHTOKEN>");
Console.WriteLine(response.OpenJsonObjectResponse().ToJsonString());
}
catch (ContentstackErrorException e)
{
Console.WriteLine(e.ErrorMessage);
}OAuth
OAuth returns an OAuthHandler that runs the Open Authorization (OAuth) 2.0 authorization code flow for one app and stores the tokens on this client.
| Name | Type | Description |
|---|---|---|
| options (required) | OAuthOptions | App ID, client ID, redirect URI, and optional secret. |
Returns: OAuthHandler. A new OAuth handler.
Overloads
- OAuth(OAuthOptions options)
- OAuth(): This overload takes no parameters. It uses the default values of OAuthOptions, which identify Contentstack's own OAuth app with the redirect URI http://localhost:8184.
Validation
- Throws ArgumentNullException if options is null, because the handler needs an app to authorize.
- Throws OAuthConfigurationException if options fails validation, for example an empty ClientId or a RedirectUri that is not an absolute http or https URI. See the Validate method of OAuthOptions for every rule.
- OAuth sends no request. Errors from the OAuth flow come from the OAuthHandler methods that follow.
Behavior
- Client-side only. OAuth creates a new handler bound to this client on every call.
- The handler stores the tokens it receives on the client, keyed by ClientId. Two handlers with the same client ID share one set of tokens.
- After a token exchange, the client sends the access token as authorization: Bearer <ACCESS_TOKEN> on every request.
- A handler keeps the Proof Key for Code Exchange (PKCE) code verifier that AuthorizeAsync creates. Call ExchangeCodeForTokenAsync or HandleRedirectAsync on the same handler instance.
- See the OAuthHandler class page for the full flow.
Example
Basic usage: start a PKCE flow for your app
using System;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
using Contentstack.Management.Core.Models;
ContentstackClient client = new ContentstackClient();
try
{
OAuthHandler oauth = client.OAuth(new OAuthOptions()
{
AppId = "<APP_ID>",
ClientId = "<CLIENT_ID>",
RedirectUri = "<REDIRECT_URI>"
});
string authorizationUrl = await oauth.AuthorizeAsync();
Console.WriteLine($"Open this URL to authorize the app: {authorizationUrl}");
}
catch (OAuthException e)
{
// Thrown when the options are invalid or the URL cannot be built
Console.WriteLine($"OAuth setup failed: {e.Message}");
}All parameters: use the default Contentstack app
using System;
using Contentstack.Management.Core;
ContentstackClient client = new ContentstackClient();
OAuthHandler oauth = client.OAuth();
Console.WriteLine($"{oauth.AppId} {oauth.ClientId} {oauth.RedirectUri} PKCE: {oauth.UsePkce}");Edge case: invalid options throw at once
using System;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
using Contentstack.Management.Core.Models;
ContentstackClient client = new ContentstackClient();
try
{
client.OAuth(new OAuthOptions() { AppId = "<APP_ID>", ClientId = "<CLIENT_ID>", RedirectUri = "localhost:8184" });
}
catch (OAuthConfigurationException e)
{
// Fires before any request, because the redirect URI has no http or https scheme
Console.WriteLine(e.Message);
}Organization
Organization returns an Organization object for one organization, or for every organization the signed-in user belongs to.
| Name | Type | Description |
|---|---|---|
| uid | string? | UID of the organization to work with. |
Returns: Organization. A new organization object.
Validation
- There is no client-side validation, and Organization sends no request.
- Errors come from the Organization methods that follow. Every method except GetOrganizations throws InvalidOperationException when uid is null or empty. See the Organization class page.
Behavior
- Client-side only. Organization creates a new object bound to this client on every call.
- Without uid, the object reaches only GetOrganizations, which then lists every organization of the signed-in user.
Example
Basic usage: list the stacks of an organization
using System;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
using Contentstack.Management.Core.Models;
ContentstackClient client = new ContentstackClient("<AUTHTOKEN>");
Organization organization = client.Organization("<ORGANIZATION_UID>");
try
{
ContentstackResponse response = organization.GetStacks();
Console.WriteLine(response.OpenJsonObjectResponse().ToJsonString());
}
catch (ContentstackErrorException e)
{
// Thrown when the API rejects the request
Console.WriteLine($"Request failed: {(int)e.StatusCode} {e.ErrorCode} {e.ErrorMessage}");
}Edge case: list every organization without a UID
using System;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
ContentstackClient client = new ContentstackClient("<AUTHTOKEN>");
try
{
ContentstackResponse response = client.Organization().GetOrganizations();
Console.WriteLine(response.OpenJsonObjectResponse().ToJsonString());
}
catch (ContentstackErrorException e)
{
Console.WriteLine(e.ErrorMessage);
}Stack
Stack returns a Stack object for one stack, optionally with a management token and a branch, or for the stack collection.
| Name | Type | Description |
|---|---|---|
| apiKey | string? | API key of the stack to work with. |
| managementToken | string? | Management token of the stack. Replaces the authtoken. |
| branchUid | string? | Branch that every request from the stack targets. |
Returns: Stack. A new stack object.
Validation
- There is no client-side validation, and Stack sends no request. The SDK does not check that the API key, the token, or the branch exists.
- Errors come from the methods you call on the stack and on the objects it creates. They throw InvalidOperationException when the client has no authtoken and managementToken is empty, and when a method needs an API key that the stack does not have. See the Stack class page.
Behavior
- Client-side only. Stack creates a new object bound to this client on every call.
- Every request from the stack sends apiKey as the api_key header.
- When managementToken has a value, every request from the stack sends it as the authorization header instead of the client's authtoken. Some Content Management API (CMA) requests accept only an authtoken. The page of each method says when the CMA reference requires one.
- When branchUid has a value, every request from the stack sends it as the branch header.
- Without apiKey, the stack reaches the requests that work across stacks, such as listing every stack or creating one.
Example
Basic usage: fetch a stack with the client's authtoken
using System;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
using Contentstack.Management.Core.Models;
ContentstackClient client = new ContentstackClient("<AUTHTOKEN>");
Stack stack = client.Stack("<API_KEY>");
try
{
ContentstackResponse response = stack.Fetch();
Console.WriteLine(response.OpenJsonObjectResponse().ToJsonString());
}
catch (ContentstackErrorException e)
{
// Thrown when the API rejects the request
Console.WriteLine($"Request failed: {(int)e.StatusCode} {e.ErrorCode} {e.ErrorMessage}");
}All parameters: a management token and a branch
using System;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
using Contentstack.Management.Core.Models;
// A management token needs no authtoken on the client.
ContentstackClient client = new ContentstackClient();
Stack stack = client.Stack("<API_KEY>", "<MANAGEMENT_TOKEN>", "<BRANCH_UID>");
try
{
ContentstackResponse response = stack.ContentType().Query().Find();
Console.WriteLine(response.OpenJsonObjectResponse().ToJsonString());
}
catch (ContentstackErrorException e)
{
Console.WriteLine(e.ErrorMessage);
}Edge case: list every stack without an API key
using System;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
ContentstackClient client = new ContentstackClient("<AUTHTOKEN>");
try
{
ContentstackResponse response = client.Stack().GetAll();
Console.WriteLine(response.OpenJsonObjectResponse().ToJsonString());
}
catch (ContentstackErrorException e)
{
Console.WriteLine(e.ErrorMessage);
}User
User returns a User object that sends the password reset requests of a Contentstack account.
This method takes no parameters.
Returns: User. A new user object.
Validation
- There is no client-side validation, and User sends no request.
- Errors come from the User methods that follow. Each one throws InvalidOperationException when the client already has an authtoken. See the User class page.
Behavior
- Client-side only. User creates a new User object bound to this client on every call.
- To read the account behind the authtoken, call GetUser on the client instead.
Example
Basic usage: request a temporary password
using System;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
using Contentstack.Management.Core.Models;
ContentstackClient client = new ContentstackClient();
User user = client.User();
try
{
ContentstackResponse response = user.ForgotPassword("<EMAIL>");
Console.WriteLine(response.OpenJsonObjectResponse().ToJsonString());
}
catch (ContentstackErrorException e)
{
// Thrown when the API rejects the request
Console.WriteLine($"Request failed: {(int)e.StatusCode} {e.ErrorCode} {e.ErrorMessage}");
}