ContentstackResponse

View as Markdown

ContentstackResponse

ContentstackResponse holds the HTTP response of one Content Management API (CMA) request and reads its body and headers.

When to Use This Class: Use this class after every request method of the SDK, such as Fetch, Create, or Find, to read the JSON the API returned.

Conceptual Role: Acts as the result type of every sync request method. Every async request method returns Task<ContentstackResponse>.

Returns: ContentstackResponse. The HTTP response of one request.

Class-Level Notes

Every response you receive is a success.

  • The SDK throws ContentstackErrorException for any status outside 2xx, so a method returns a ContentstackResponse only for a 2xx status.
  • The default .NET HTTP handler follows a redirect before the SDK sees it. A 3xx status that reaches the SDK, such as 304, throws ContentstackErrorException like a 4xx status.

The body is raw JSON.

  • The SDK does not map the body to a model. The JSON keys are the ones the CMA reference lists for the request, usually with the item under a wrapper key, such as entry or content_types.
  • Read it as text with OpenResponse, as a JsonObject with OpenJsonObjectResponse, or as your own type with OpenTResponse.
  • You can read the body more than once and in more than one form.

Class-Level Properties

PropertyTypeAccessDefaultDescription
StatusCodeHttpStatusCodeRead-onlyThe response statusHTTP status code of the response.
IsSuccessStatusCodeboolRead-onlyThe response valuetrue for a 2xx status, which every returned response has.
ContentTypestring?Read-onlyThe response media typeMedia type of the body, such as application/json. null when the response has none.
ContentLengthlongRead-onlyThe response lengthLength of the body in bytes. 0 when the response sends no length.
ResponseBodyHttpResponseMessageRead-onlyThe response messageThe underlying .NET response, with every header and the raw content.

Method Index

Read the body.

Method NameReturnsDescription
OpenJsonObjectResponseThe response body as a JSON object.Parses the body into a JsonObject.
OpenTResponseThe response body as an object of your type.Deserializes the body into a type you choose.
OpenResponseThe response body as a string.Reads the body as text.

Read the headers.

Method NameReturnsDescription
GetHeaderNamesThe names of the response headers.Lists every header name.
GetHeaderValueThe first value of the header.Reads one header value.
IsHeaderPresentTrue when the response has the header.Checks for a header.

Release the response.

Method NameReturnsDescription
DisposeThis method returns nothing.Blocks later reads of the body.

Class-Level Snippet

This snippet fetches a content type, prints the status and media type, and reads its title from the JSON body.

using System;
using System.Text.Json.Nodes;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;

ContentstackClient client = new ContentstackClient("<AUTHTOKEN>");

try
{
    ContentstackResponse response = client.Stack("<API_KEY>").ContentType("<CONTENT_TYPE_UID>").Fetch();
    Console.WriteLine($"{(int)response.StatusCode} {response.ContentType}");

    JsonObject body = response.OpenJsonObjectResponse();
    Console.WriteLine(body["content_type"]?["title"]);
}
catch (ContentstackErrorException e)
{
    Console.WriteLine($"Request failed: {(int)e.StatusCode} {e.ErrorCode} {e.ErrorMessage}");
}

Methods

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

Dispose

Dispose marks the response as disposed, so later reads of the body throw.

This method takes no parameters.

Returns: void. This method returns nothing.

Validation

  • There is no client-side validation. A second call does nothing.

Behavior

  • Client-side only. Dispose sends no request.
  • After Dispose, OpenResponse, OpenJsonObjectResponse, and OpenTResponse throw ObjectDisposedException.
  • The header methods and the properties still return their values.
  • Dispose does not dispose ResponseBody, the underlying HttpResponseMessage. Dispose it yourself when you no longer need it.

Example

Basic usage: dispose the response with a using declaration

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

ContentstackClient client = new ContentstackClient("<AUTHTOKEN>");

try
{
    using ContentstackResponse response = client.Stack("<API_KEY>").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}");
}

Edge case: reading the body after Dispose

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

ContentstackClient client = new ContentstackClient("<AUTHTOKEN>");

try
{
    ContentstackResponse response = client.Stack("<API_KEY>").Fetch();
    response.Dispose();

    Console.WriteLine(response.GetHeaderValue("content-type"));
    response.OpenResponse();
}
catch (ObjectDisposedException e)
{
    // Fires on OpenResponse, because the response is disposed
    Console.WriteLine(e.Message);
}
catch (ContentstackErrorException e)
{
    Console.WriteLine(e.ErrorMessage);
}

GetHeaderNames

GetHeaderNames lists the names of the response headers and the content headers.

This method takes no parameters.

Returns: string[]. The names of the response headers.

Validation

  • There is no client-side validation. GetHeaderNames returns an empty array when the response has no headers.

Behavior

  • Client-side only. GetHeaderNames reads the headers the SDK copied when it received the response, and sends no request.
  • Lists the response headers first, then the content headers, such as Content-Type, that the response headers did not already name.
  • Works after Dispose.

Example

Basic usage: print every header with its value

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

ContentstackClient client = new ContentstackClient("<AUTHTOKEN>");

try
{
    ContentstackResponse response = client.Stack("<API_KEY>").Fetch();

    foreach (string name in response.GetHeaderNames())
    {
        Console.WriteLine($"{name}: {response.GetHeaderValue(name)}");
    }
}
catch (ContentstackErrorException e)
{
    // Thrown when the API rejects the request
    Console.WriteLine($"Request failed: {(int)e.StatusCode} {e.ErrorCode} {e.ErrorMessage}");
}

GetHeaderValue

GetHeaderValue reads the value of one response header.

NameTypeDescription
headerName (required)string

Name of the header to read. Case-insensitive.

Default: Not applicable

Returns: string. The first value of the header.

Validation

  • Returns an empty string when the response has no header of that name. It does not throw.
  • Throws ArgumentNullException if headerName is null.

Behavior

  • Client-side only. GetHeaderValue reads the headers the SDK copied when it received the response, and sends no request.
  • Matches the name without regard to case, so content-type and Content-Type return the same value.
  • Returns only the first value of a header that has several. Read ResponseBody.Headers for every value.
  • Works after Dispose.

Example

Basic usage: read the media type of the body

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

ContentstackClient client = new ContentstackClient("<AUTHTOKEN>");

try
{
    ContentstackResponse response = client.Stack("<API_KEY>").Fetch();
    Console.WriteLine(response.GetHeaderValue("content-type"));
}
catch (ContentstackErrorException e)
{
    // Thrown when the API rejects the request
    Console.WriteLine($"Request failed: {(int)e.StatusCode} {e.ErrorCode} {e.ErrorMessage}");
}

Edge case: a header the response does not have

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

ContentstackClient client = new ContentstackClient("<AUTHTOKEN>");

try
{
    ContentstackResponse response = client.Stack("<API_KEY>").Fetch();

    // Prints True: a missing header returns an empty string, not null.
    Console.WriteLine(response.GetHeaderValue("<HEADER_NAME>") == string.Empty);
}
catch (ContentstackErrorException e)
{
    Console.WriteLine(e.ErrorMessage);
}

IsHeaderPresent

IsHeaderPresent checks whether the response has a header of a given name.

NameTypeDescription
headerName (required)string

Name of the header to look for. Case-insensitive.

Default: Not applicable

Returns: bool. True when the response has the header.

Validation

  • There is no client-side validation. IsHeaderPresent returns false for a null name. It does not throw.

Behavior

  • Client-side only. IsHeaderPresent reads the headers the SDK copied when it received the response, and sends no request.
  • Matches the name without regard to case, and checks the response headers and the content headers.
  • Use it to tell a missing header from an empty one, because GetHeaderValue returns an empty string for both.

Example

Basic usage: read a header only when it is present

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

ContentstackClient client = new ContentstackClient("<AUTHTOKEN>");

try
{
    ContentstackResponse response = client.Stack("<API_KEY>").Fetch();

    if (response.IsHeaderPresent("<HEADER_NAME>"))
    {
        Console.WriteLine(response.GetHeaderValue("<HEADER_NAME>"));
    }
}
catch (ContentstackErrorException e)
{
    // Thrown when the API rejects the request
    Console.WriteLine($"Request failed: {(int)e.StatusCode} {e.ErrorCode} {e.ErrorMessage}");
}

OpenJsonObjectResponse

OpenJsonObjectResponse parses the response body into a System.Text.Json.Nodes.JsonObject.

This method takes no parameters.

Returns: JsonObject. The response body as a JSON object.

Validation

  • Throws ObjectDisposedException if you called Dispose on the response, because the SDK blocks reads after it.
  • Throws JsonException if the body is empty or is not JSON, for example an image download.
  • Throws InvalidOperationException if the body is JSON but its root is not an object, for example an array.

Behavior

  • Client-side only. OpenJsonObjectResponse reads the body that the request already received and sends no request.
  • Each call parses the body again and returns a new JsonObject. A change to one object does not reach the next call's result.
  • Use the indexer to read a key, for example body["entry"]?["title"]. A missing key returns null.

Example

Basic usage: read a field of a fetched entry

using System;
using System.Text.Json.Nodes;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;

ContentstackClient client = new ContentstackClient("<AUTHTOKEN>");

try
{
    ContentstackResponse response = client.Stack("<API_KEY>").ContentType("<CONTENT_TYPE_UID>").Entry("<ENTRY_UID>").Fetch();
    JsonObject body = response.OpenJsonObjectResponse();
    Console.WriteLine(body["entry"]?["title"]);
}
catch (ContentstackErrorException e)
{
    // Thrown when the API rejects the request
    Console.WriteLine($"Request failed: {(int)e.StatusCode} {e.ErrorCode} {e.ErrorMessage}");
}

Edge case: iterate over a list in the body

using System;
using System.Text.Json.Nodes;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;

ContentstackClient client = new ContentstackClient("<AUTHTOKEN>");

try
{
    ContentstackResponse response = client.Stack("<API_KEY>").ContentType().Query().Find();
    JsonArray? contentTypes = response.OpenJsonObjectResponse()["content_types"]?.AsArray();

    foreach (JsonNode? contentType in contentTypes ?? new JsonArray())
    {
        Console.WriteLine(contentType?["uid"]);
    }
}
catch (ContentstackErrorException e)
{
    Console.WriteLine(e.ErrorMessage);
}

OpenResponse

OpenResponse reads the response body as a string.

This method takes no parameters.

Returns: string. The response body as a string.

Validation

  • Throws ObjectDisposedException if you called Dispose on the response.
  • Returns an empty string when the body is empty. It does not throw.

Behavior

  • Client-side only. OpenResponse reads the body that the request already received and sends no request.
  • Reads the body as UTF-8 text, or in the character set that the Content-Type header names.
  • Blocks the calling thread while it reads the body.
  • OpenJsonObjectResponse and OpenTResponse call OpenResponse first.

Example

Basic usage: print the raw JSON

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

ContentstackClient client = new ContentstackClient("<AUTHTOKEN>");

try
{
    ContentstackResponse response = client.Stack("<API_KEY>").Fetch();
    string json = response.OpenResponse();
    Console.WriteLine(json);
}
catch (ContentstackErrorException e)
{
    // Thrown when the API rejects the request
    Console.WriteLine($"Request failed: {(int)e.StatusCode} {e.ErrorCode} {e.ErrorMessage}");
}

OpenTResponse

OpenTResponse deserializes the response body into an object of the type you pass as TResponse.

This method takes no parameters. The type argument TResponse is the class the SDK maps the whole response body onto.

Returns: TResponse. The response body as an object of your type.

Validation

  • Throws ObjectDisposedException if you called Dispose on the response.
  • Throws JsonException if the body is not JSON, or if a JSON value cannot convert to the matching property type.
  • Returns null when the body is the JSON literal null. The method skips a JSON key with no matching property without an error.

Behavior

  • Client-side only. OpenTResponse reads the body that the request already received and sends no request.
  • Deserializes with the client's SerializerOptions, so property names match JSON keys without regard to case, and the SDK's converters for fields and rich text nodes apply.
  • TResponse describes the whole body, including the wrapper key. For a fetched entry, the body is {"entry": {...}}, so TResponse needs an Entry property, or read the inner node with OpenJsonObjectResponse and deserialize that.
  • Use [JsonPropertyName] from System.Text.Json.Serialization when a property name differs from its JSON key, for example content_type.

Example

Basic usage: map a fetched entry onto your own classes

using System;
using System.Text.Json.Serialization;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;

ContentstackClient client = new ContentstackClient("<AUTHTOKEN>");

try
{
    ContentstackResponse response = client.Stack("<API_KEY>").ContentType("<CONTENT_TYPE_UID>").Entry("<ENTRY_UID>").Fetch();
    EntryResponse? body = response.OpenTResponse<EntryResponse>();
    Console.WriteLine($"{body?.Entry?.Title}: {body?.Entry?.Url}");
}
catch (ContentstackErrorException e)
{
    // Thrown when the API rejects the request
    Console.WriteLine($"Request failed: {(int)e.StatusCode} {e.ErrorCode} {e.ErrorMessage}");
}

public class EntryResponse
{
    public BlogPost? Entry { get; set; }
}

public class BlogPost
{
    public string? Uid { get; set; }
    public string? Title { get; set; }
    public string? Url { get; set; }

    [JsonPropertyName("created_at")]
    public DateTime CreatedAt { get; set; }
}