Configuration API for C# SDK
C# complete API reference for building real-time applications on PubNub, including basic usage and sample code.
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.
1try
2{
3 PNResult<PNPublishResult> publishResponse = await pubnub.Publish()
4 .Message("Why do Java developers wear glasses? Because they can't C#.")
5 .Channel("my_channel")
6 .ExecuteAsync();
7
8 PNStatus status = publishResponse.Status;
9
10 Console.WriteLine("Server status code : " + status.StatusCode.ToString());
11}
12catch (Exception ex)
13{
14 Console.WriteLine($"Request can't be executed due to error: {ex.Message}");
15}
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:
1
| Parameter | Description |
|---|---|
SubscribeKey *Type: string | SubscribeKey from Admin Portal. |
PublishKeyType: string | PublishKey from Admin Portal (only required if publishing). |
SecretKeyType: string | SecretKey required for access control operations. |
UserId *Type: UserId | 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 theUserId, you won't be able to connect to PubNub. |
LogLevelType: PubnubLogLevel | Enum defining the level of severity captured in logs. Available values:
PubnubLogLevel.None (logging off). See Logging. |
AuthKeyType: string | If Access Manager is utilized, client will use this AuthKey in all restricted requests. |
SecureType: bool | Use SSL. |
SubscribeTimeoutType: int | How long to keep the subscribe loop running before disconnect (seconds). |
NonSubscribeRequestTimeoutType: int | How long to wait for a response on non-subscribe operations (seconds). |
FilterExpressionType: string | Subscribe with a custom filter expression. |
HeartbeatNotificationOptionType: PNHeartbeatNotificationOption | Heartbeat notifications. Default: failures only (PNHeartbeatNotificationOption.FAILURES). Other options: all (PNHeartbeatNotificationOption.ALL) or none (PNHeartbeatNotificationOption.NONE). |
OriginType: string | Custom Origin if needed. To request a custom domain, contact support and follow the request process. |
ReconnectionPolicyType: PNReconnectionPolicy | Custom reconnection configuration parameters. Default is PNReconnectionPolicy.EXPONENTIAL (subscribe only). Available values:
For more information, refer to SDK connection lifecycle. |
ConnectionMaxRetriesType: int | Maximum reconnection attempts. If unset, the SDK does not reconnect. See Reconnection Policy. |
PresenceTimeoutType: int | 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. |
SetPresenceTimeoutWithCustomIntervalType: int | How often the client sends heartbeat signals. More granular than PresenceTimeout. Recommended: (PresenceTimeout / 2) - 1. |
ProxyType: Proxy | Instructs the SDK to use a Proxy configuration when communicating with PubNub servers. |
RequestMessageCountThresholdType: Number | Threshold for messages per payload. Exceeding this triggers PNRequestMessageCountExceededCategory. |
SuppressLeaveEventsType: bool | When true, the SDK does not send leave requests. |
DedupOnSubscribeType: bool | When true, filters duplicate subscribe messages across regions. |
MaximumMessagesCacheSizeType: int | Used with DedupOnSubscribe to cache message size. Default: 100. |
FileMessagePublishRetryLimitType: int | Retries for file message publish failures. Default: 5. |
CryptoModuleType: AesCbcCryptor(CipherKey) LegacyCryptor(CipherKey) | 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 section. |
EnableEventEngineType: Boolean | 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 it emits. |
MaintainPresenceStateType: Boolean | This option works only when EnableEventEngine is set to true. Whether the custom presence state information set using pubnub.setPresenceState() should be sent every time the SDK sends a subscribe call. |
RetryConfigurationType: RetryConfiguration | (When enableEventEngine = true) Custom reconnection configuration. Options:
|
LogVerbosityType: PNLogVerbosity | This parameter is deprecated, use LogLevel instead.PNLogVerbosity.BODY to enable debugging. To disable debugging use the option PNLogVerbosity.NONE |
PubnubLogType: IPubnubLog | This parameter is deprecated, use the SetLogger method to configure a custom logger that implements the IPubnubLogger interface.IPubnubLog to capture logs for troubleshooting. |
CipherKeyType: | This way of setting this parameter is deprecated, pass it to CryptoModule instead. cipher is passed, all communications to/from PubNub will be encrypted. |
UseRandomInitializationVectorType: | This way of setting this parameter is deprecated, pass it to CryptoModule instead. 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. |
UuidType: | 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 and 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 page.
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
Reference code
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.
1
Initialization
Include the code
1