---
source_url: https://www.pubnub.com/docs/sdks/c-sharp/api-reference/configuration
title: Configuration API for C# SDK
updated_at: 2026-06-04T11:11:12.597Z
sdk_name: PubNub C# SDK
sdk_version: 8.2.1
---

> Documentation Index
> For a curated overview of PubNub documentation, see: https://www.pubnub.com/docs/llms.txt
> For the full list of all documentation pages, see: https://www.pubnub.com/docs/llms-full.txt


# Configuration API for C# SDK

PubNub C# SDK, use the latest version: 8.2.1

Install:

```bash
dotnet add package PubNub@8.2.1
```

C# complete API reference for building real-time applications on PubNub, including basic usage and sample code.

:::tip Request execution
Use `try`/`catch` when working with the C# SDK.
If a request has invalid parameters (for example, a missing required field), the SDK throws an exception. If the request reaches the server but fails (server error or network issue), the error details are available in the returned `status`.
```csharp
try
{
    PNResult<PNPublishResult> publishResponse = await pubnub.Publish()
        .Message("Why do Java developers wear glasses? Because they can't C#.")
        .Channel("my_channel")
        .ExecuteAsync();
    PNStatus status = publishResponse.Status;
    Console.WriteLine("Server status code : " + status.StatusCode.ToString());
}
catch (Exception ex)
{
    Console.WriteLine($"Request can't be executed due to error: {ex.Message}");
}
```
:::

## Configuration

`PNConfiguration` stores user-provided settings that control how the C# Software Development Kit (SDK) behaves. Use these properties to fine-tune client behavior and get a prototype running fast.

### Method(s)

To create `configuration` instance you can use the following function in the C# SDK:

```csharp
using PubnubApi;

PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId"));
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| SubscribeKey | string | Yes |  | `SubscribeKey` from Admin Portal. |
| PublishKey | string | Optional |  | `PublishKey` from Admin Portal (only required if publishing). |
| SecretKey | string | Optional |  | `SecretKey` required for access control operations. |
| UserId | UserId | Yes |  | `UserId` to use. The `UserId` object takes `string` as an argument. You should set a unique identifier for the user or the device that connects to PubNub. It's a UTF-8 encoded string of up to 92 alphanumeric characters. If you don't set the `UserId`, you won't be able to connect to PubNub. |
| LogLevel | PubnubLogLevel | Optional |  | Enum defining the level of severity captured in logs. Available values:PubnubLogLevel.Trace, PubnubLogLevel.Debug, PubnubLogLevel.Info, PubnubLogLevel.Warn, PubnubLogLevel.ErrorDefault: `PubnubLogLevel.None` (logging off). See [Logging](https://www.pubnub.com/docs/sdks/c-sharp/logging#how-to-enable-logging). |
| AuthKey | string | Optional |  | If Access Manager is utilized, client will use this `AuthKey` in all restricted requests. |
| Secure | bool | Optional |  | Use `SSL`. |
| SubscribeTimeout | int | Optional |  | How long to keep the subscribe loop running before disconnect (seconds). |
| NonSubscribeRequestTimeout | int | Optional |  | How long to wait for a response on non-subscribe operations (seconds). |
| FilterExpression | string | Optional |  | Subscribe with a custom filter expression. |
| HeartbeatNotificationOption | PNHeartbeatNotificationOption | Optional |  | Heartbeat notifications. Default: failures only (`PNHeartbeatNotificationOption.FAILURES`). Other options: all (`PNHeartbeatNotificationOption.ALL`) or none (`PNHeartbeatNotificationOption.NONE`). |
| Origin | string | Optional |  | Custom `Origin` if needed. []() To request a custom domain, contact support and follow the [request process](https://www.pubnub.com/docs/general/setup/data-security#request-process). |
| ReconnectionPolicy | PNReconnectionPolicy | Optional |  | Custom reconnection configuration parameters. Default is `PNReconnectionPolicy.EXPONENTIAL` (subscribe only). Available values: PNReconnectionPolicy.NONE, PNReconnectionPolicy.LINEAR, PNReconnectionPolicy.EXPONENTIAL For more information, refer to [SDK connection lifecycle](https://www.pubnub.com/docs/general/setup/connection-management#sdk-connection-lifecycle). |
| ConnectionMaxRetries | int | Optional |  | Maximum reconnection attempts. If unset, the SDK does not reconnect. See [Reconnection Policy](https://www.pubnub.com/docs/general/setup/connection-management#reconnection-policy). |
| PresenceTimeout | int | Optional |  | How long the server considers the client alive for Presence. The SDK sends periodic heartbeats (for example, every 300 seconds) to keep the client active. If no heartbeat arrives within the timeout, the client is marked inactive and a "timeout" event is emitted on the [presence channel](https://www.pubnub.com/docs/general/presence/overview). |
| SetPresenceTimeoutWithCustomInterval | int | Optional |  | How often the client sends heartbeat signals. More granular than `PresenceTimeout`. Recommended: `(PresenceTimeout / 2) - 1`. |
| Proxy | Proxy | Optional |  | Instructs the SDK to use a `Proxy` configuration when communicating with PubNub servers. |
| RequestMessageCountThreshold | Number | Optional |  | Threshold for messages per payload. Exceeding this triggers `PNRequestMessageCountExceededCategory`. |
| SuppressLeaveEvents | bool | Optional |  | When `true`, the SDK does not send leave requests. |
| DedupOnSubscribe | bool | Optional |  | When `true`, filters duplicate subscribe messages across regions. |
| MaximumMessagesCacheSize | int | Optional |  | Used with `DedupOnSubscribe` to cache message size. Default: `100`. |
| FileMessagePublishRetryLimit | int | Optional |  | Retries for file message publish failures. Default: `5`. |
| CryptoModule | AesCbcCryptor(CipherKey) | Optional |  | The cryptography module used for encryption and decryption of messages and files. Takes the `CipherKey` parameter as argument. For more information, refer to the [CryptoModule](#cryptomodule) section. |
| EnableEventEngine | Boolean | Optional |  | True by default. Whether to use the recommended standardized workflows for subscribe and presence, optimizing how the SDK internally handles these operations and which [statuses](https://www.pubnub.com/docs/sdks/c-sharp/status-events) it emits. |
| MaintainPresenceState | Boolean | Optional |  | This option works only when `EnableEventEngine` is set to `true`. Whether the custom presence state information set using [pubnub.setPresenceState()](https://www.pubnub.com/docs/sdks/c-sharp/api-reference/presence#set-state) should be sent every time the SDK sends a subscribe call. |
| RetryConfiguration | RetryConfiguration | Optional |  | (When `enableEventEngine = true`) Custom reconnection configuration. Options: RetryConfiguration.Linear(int delayInSecond, int maxRetry), RetryConfiguration.Exponential(int minDelayInSecond, int maxDelayInSecond, int maxRetry) See [Reconnection Policy](https://www.pubnub.com/docs/general/setup/connection-management#reconnection-policy). Excluding endpoints is not supported. |
| LogVerbosity | PNLogVerbosity | Optional |  | This parameter is deprecated, use `LogLevel` instead. Set PNLogVerbosity.BODY to enable debugging. To disable debugging use the option PNLogVerbosity.NONE |
| PubnubLog | IPubnubLog | Optional |  | This parameter is deprecated, use the `SetLogger` method to configure a custom logger that implements the `IPubnubLogger` interface. Pass the instance of a class that implements IPubnubLog to capture logs for troubleshooting. |
| CipherKey | string | Optional |  | This way of setting this parameter is deprecated, pass it to `CryptoModule` instead. If cipher is passed, all communications to/from PubNub will be encrypted. |
| UseRandomInitializationVector | bool | Optional |  | This way of setting this parameter is deprecated, pass it to `CryptoModule` instead. When true the IV will be random for all requests and not just file upload. When false the IV will be hardcoded for all requests except File Upload. Default false. |
| Uuid | string | Yes |  | This parameter is deprecated, use `userId` instead. UUID to use. You should set a unique UUID to identify the user or the device that connects to PubNub. If you don't set the UUID, you won't be able to connect to PubNub. |

#### CryptoModule

`CryptoModule` encrypts and decrypts messages and files. From 6.18.0 onward, you can configure the algorithms it uses.

Each SDK includes two options: legacy 128-bit encryption and recommended 256-bit AES-CBC. For background, see [Message Encryption](https://www.pubnub.com/docs/general/setup/data-security#message-encryption) and [File Encryption](https://www.pubnub.com/docs/general/setup/data-security#file-encryption).

If you do not explicitly set the `CryptoModule` in your app and have the `CipherKey` and `UseRandomInitializationVector` params set in PubNub config, the client defaults to using the legacy encryption.

For detailed encryption configuration, utility methods for encrypting/decrypting messages and files, and practical examples, see the dedicated [Encryption](https://www.pubnub.com/docs/sdks/c-sharp/api-reference/encryption) page.

:::note Legacy encryption with 128-bit cipher key entropy
You don't have to change your encryption configuration if you want to keep using the legacy encryption. If you want to use the recommended 256-bit AES-CBC encryption, you must explicitly set that in PubNub config.
:::

### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

:::note Required User ID
Always set the `UserId` to uniquely identify the user or device that connects to PubNub. This `UserId` should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the `UserId`, you won't be able to connect to PubNub.
:::

```csharp
using PubnubApi;

// Create a configuration instance for PubNub
PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId"))
{
    SubscribeKey = "demo", // Required
    PublishKey = "demo",   // Only required if publishing
    SecretKey = "SecretKey", // Only required for access operations
    Secure = true, // Enable SSL
    AuthKey = "authKey", // If Access Manager is utilized
    LogLevel = PubnubLogLevel.Debug, // Enable debugging
    SubscribeTimeout = 310, // Subscribe loop timeout in seconds
    NonSubscribeRequestTimeout = 300, // Non-subscribe request timeout
    FilterExpression = "such=wow", // PSV2 filter expression
    HeartbeatNotificationOption = PNHeartbeatNotificationOption.All, // Heartbeat notifications
    PresenceTimeout = 120, // Presence timeout
};

// Configure presence timeout with custom interval
pnConfiguration.SetPresenceTimeoutWithCustomInterval(120, 59);

// Encryption configuration (Optional)
pnConfiguration.CryptoModule = new CryptoModule(
    new AesCbcCryptor("enigma"), 
    new List<ICryptor> { new LegacyCryptor("enigma") });

// Initialize a new PubNub instance with the created confiiguration
Pubnub pubnub = new Pubnub(pnConfiguration);
```

## Initialization

#### Include the code

```csharp
using PubnubApi;

```

### Description

Initialize the PubNub client and set credentials such as `PublishKey` and `SubscribeKey`.

### Method(s)

To `Initialize` PubNub you can use the following method(s) in the C# SDK:

```csharp
using PubnubApi;

Pubnub pubnub = new Pubnub(pnConfiguration);
        
```

| Parameter | Description |
| --- | --- |
| `pnConfiguration` *Type: PNConfiguration | Go to [Configuration](#configuration) for more details. |

### Sample code

#### Initialize the PubNub client API

:::note Required User ID
Always set the `UserId` to uniquely identify the user or device that connects to PubNub. This `UserId` should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the `UserId`, you won't be able to connect to PubNub.
:::

```csharp
using PubnubApi;

// Initialize PubNub using the configuration
PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId"))
{
    SubscribeKey = "demo",
    PublishKey = "demo",
    Secure = true
};

// Create the PubNub instance with the configuration
Pubnub pubnub = new Pubnub(pnConfiguration);
```

### Returns

Returns a PubNub instance for APIs like `Publish()`, `Subscribe()`, `History()`, and `HereNow()`.

### Other examples

#### Initialize a non-secure client

:::note Required User ID
Always set the `UserId` to uniquely identify the user or device that connects to PubNub. This `UserId` should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the `UserId`, you won't be able to connect to PubNub.
:::

```csharp
using PubnubApi;

PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId"));
pnConfiguration.PublishKey = "my_pubkey";
pnConfiguration.SubscribeKey = "my_subkey";
pnConfiguration.Secure = false;
Pubnub pubnub = new Pubnub(pnConfiguration);
```

#### Initialization for a Read-Only client

In the case where a client will only read messages and never publish to a channel, you can simply omit the `PublishKey` when initializing the client:

:::note Required User ID
Always set the `UserId` to uniquely identify the user or device that connects to PubNub. This `UserId` should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the `UserId`, you won't be able to connect to PubNub.
:::

```csharp
using PubnubApi;

PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId"));
pnConfiguration.SubscribeKey = "my_subkey";
Pubnub pubnub = new Pubnub(pnConfiguration);
```

#### Initializing with SSL enabled

This example shows how to enable Transport Layer Encryption (SSL). Initialize the client with `Secure` set to `true`, then subscribe and publish as usual.

:::note Required User ID
Always set the `UserId` to uniquely identify the user or device that connects to PubNub. This `UserId` should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the `UserId`, you won't be able to connect to PubNub.
:::

```csharp
using PubnubApi;

PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId"));
pnConfiguration.PublishKey = "my_pubkey";
pnConfiguration.SubscribeKey = "my_subkey";
pnConfiguration.Secure = true;
Pubnub pubnub = new Pubnub(pnConfiguration);
```

:::note Requires Access Manager add-on
This method requires that the *Access Manager* add-on is enabled for your key in the [Admin Portal](https://admin.pubnub.com/). Read the [support page](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) on enabling add-on features on your keys.
:::

:::note Secure your secretKey
Anyone with the `SecretKey` can grant and revoke permissions to your app. Never let your `SecretKey` be discovered, and to only exchange it / deliver it securely. Only use the `SecretKey` on secure server-side platforms.
When you init with `SecretKey`, you get root permissions for the Access Manager. With this feature you don't have to grant access to your servers to access channel data. The servers get all access on all channels.
:::

For applications that will administer Access Manager permissions, the API is initialized with the `SecretKey` as in the following example:

:::note Required User ID
Always set the `UserId` to uniquely identify the user or device that connects to PubNub. This `UserId` should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the `UserId`, you won't be able to connect to PubNub.
:::

```csharp
using PubnubApi;

PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId"));
pnConfiguration.PublishKey = "my_pubkey";
pnConfiguration.SubscribeKey = "my_subkey";
pnConfiguration.SecretKey = "my_secretkey";
pnConfiguration.Secure = true;

Pubnub pubnub = new Pubnub(pnConfiguration);
```

After initialization with `SecretKey`, the client can access Access Manager functions. The client signs Access Manager messages with the `SecretKey`.

## Event listeners

PubNub SDKs provide several sources for real-time updates:

* The PubNub client can receive updates from all subscriptions: all channels, channel groups, channel metadata, and users.
* The [Subscription](https://www.pubnub.com/docs/sdks/c-sharp/api-reference/publish-and-subscribe#create-a-subscription) object can receive updates only for the particular object for which it was created: channel, channel group, channel metadata, or user.
* The [SubscriptionsSet](https://www.pubnub.com/docs/sdks/c-sharp/api-reference/publish-and-subscribe#create-a-subscription-set) object can receive updates for all objects for which a list of subscription objects was created.

To work with these sources, the SDK provides local representations of server entities, so you can subscribe and add handlers per entity. For details, see [Publish & Subscribe](https://www.pubnub.com/docs/sdks/c-sharp/api-reference/publish-and-subscribe#event-listeners).

## UserId

Set or get the user ID at runtime.

### Property(s)

To set/get `UserId` you can use the following property(s) in C# SDK:

```csharp
pnConfiguration.UserId = new UserId("myUserId");
```

| Property | Description |
| --- | --- |
| `UserId` *Type: string | `UserId` to be used as a device identifier. If you don't set the `UserId`, you won't be able to connect to PubNub. |

```csharp
pubnub.GetCurrentUserId();
```

This method doesn't take any arguments.

### Sample code

#### Set user ID

:::note Required User ID
Always set the `UserId` to uniquely identify the user or device that connects to PubNub. This `UserId` should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the `UserId`, you won't be able to connect to PubNub.
:::

```csharp
using PubnubApi;

//Setting the initial UserId
PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId"));
//Changing to a new UserId
pnConfiguration.UserId = new UserId("myUserId");
```

#### Get user ID

```csharp
UserId currentUserId = pubnub.GetCurrentUserId();
```

## Authentication key

Set and get the user authentication key.

### Property(s)

```csharp
pnConfiguration.AuthKey
```

| Property | Description |
| --- | --- |
| `AuthKey` *Type: string | If Access Manager is utilized, client will use this `AuthKey` in all restricted requests. |

This method doesn't take any arguments.

### Sample code

#### Set auth key

```csharp
PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId"));
pnConfiguration.AuthKey = "authKey";
```

#### Get auth key

```csharp
string sampleAuthKey = pnConfiguration.AuthKey;
```

### Returns

`Get Auth key` returns the current authentication key.

## Filter expression

:::note Requires Stream Controller add-on
This method requires that the *Stream Controller* add-on is enabled for your key in the [Admin Portal](https://admin.pubnub.com/). Read the [support page](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) on enabling add-on features on your keys.
:::

Stream filtering lets a subscriber receive only messages that match a filter. The client sets the filter, and the server applies it to block unmatched messages.

Use the following property to set or get message filters. For details, see [Publish Messages](https://www.pubnub.com/docs/general/messages/publish).

### Property(s)

```csharp
FilterExpression
```

| Property | Description |
| --- | --- |
| `FilterExpression` *Type: string | PSV2 feature to `Subscribe` with a custom filter expression. |

```csharp
pnConfiguration.FilterExpression;
```

This method doesn't take any arguments.

### Sample code

#### Set filter expression

:::note Required User ID
Always set the `UserId` to uniquely identify the user or device that connects to PubNub. This `UserId` should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the `UserId`, you won't be able to connect to PubNub.
:::

```csharp
PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId"));
pnConfiguration.FilterExpression = "such=wow";
```

#### Get filter expression

```csharp
string filterExpression = pnConfiguration.FilterExpression;
```

## Terms in this document

* **PubNub** - PubNub is a real-time messaging platform that provides APIs and SDKs for building scalable applications. It handles the complex infrastructure of real-time communication, including: Message delivery and persistence, Presence detection, Access control, Push notifications, File sharing, Serverless processing with Functions and Events & Actions, Analytics and monitoring with BizOps Workspace, AI-powered insights with Illuminate.