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.
Reuse the client instance
Create one PubNub client and reuse it for the lifetime of the user or session. Don't call new Pubnub(pnConfiguration) for every publish or operation. When a client is no longer needed, call Destroy() to release its connections and background resources.
For more information, refer to Reuse the client instance.
Method(s)
To create configuration instance you can use the following function in the C# SDK:
1
SubscribeKeyrequired#SubscribeKeyfrom Admin Portal.PublishKey#PublishKeyfrom Admin Portal (only required if publishing).SecretKey#SecretKeyrequired for access control operations.UserIdrequired#UserIdto use. TheUserIdobject takesstringas 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.LogLevel#- Enum defining the level of severity captured in logs.
Available values:PubnubLogLevel.AllPubnubLogLevel.TracePubnubLogLevel.DebugPubnubLogLevel.InfoPubnubLogLevel.WarnPubnubLogLevel.ErrorPubnubLogLevel.None
PubnubLogLevel.None(logging off). See Logging. AuthKey#- If Access Manager is utilized, client will use this
AuthKeyin all restricted requests. Secure#- Use
SSL. Default:true. SubscribeTimeout#- How long to keep the subscribe loop running before disconnect (seconds). Default:
310. NonSubscribeRequestTimeout#- How long to wait for a response on non-subscribe operations (seconds). Default:
15. FilterExpression#- Subscribe with a custom filter expression.
HeartbeatNotificationOption#- Heartbeat notifications. Default: failures only (
PNHeartbeatNotificationOption.Failures). Other options: all (PNHeartbeatNotificationOption.All) or none (PNHeartbeatNotificationOption.None). Origin#- Custom
Originif needed. Default:ps.pndsn.com.
To request a custom domain, contact support and follow the request process. ReconnectionPolicy#- Custom reconnection configuration parameters. Default is
PNReconnectionPolicy.EXPONENTIAL(subscribe only).
Available values:
PNReconnectionPolicy.NONEPNReconnectionPolicy.LINEARPNReconnectionPolicy.EXPONENTIAL
For more information, refer to SDK connection lifecycle. PresenceTimeout#- 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. The value is in seconds. Default:
300. Setting it also setsPresenceIntervalto(PresenceTimeout / 2) - 1. PresenceInterval#- How often the client sends heartbeat signals, in seconds. Read-only. To set it, use
SetPresenceTimeoutWithCustomInterval(). SetPresenceTimeoutWithCustomInterval(int timeout, int interval)#- Sets
PresenceTimeoutandPresenceInterval(both in seconds) in one call and returns thePNConfigurationinstance. More granular than settingPresenceTimeoutalone. Recommended interval:(timeout / 2) - 1. Proxy#- Instructs the SDK to use a
Proxyconfiguration when communicating with PubNub servers. RequestMessageCountThreshold#- Threshold for messages per payload. Exceeding this triggers
PNRequestMessageCountExceededCategory. Default:100. EnableHttp2#- When
true, the SDK requests HTTP/2 on supported origins and falls back to HTTP/1.1 when HTTP/2 is not available. Default istrue. HTTP/2 is available only on origins that advertise h2 support; custom origins require HTTP/2 to be explicitly enabled. Refer to HTTP/2 for more details. SuppressLeaveEvents#- When
true, the SDK does not send leave requests. Default:false. DedupOnSubscribe#- When
true, filters duplicate subscribe messages across regions. Default:false. MaximumMessagesCacheSize#- Used with
DedupOnSubscribeto cache message size. Default:100. FileMessagePublishRetryLimit#- Retries for file message publish failures. Default:
5. SplitSubscribeCalls#- When
true, the SDK changes a multi-channel subscription into multiple single-channel subscriptions. Enable it if your keyset has channel-based sharding enabled. RequiresEnableEventEngineto betrue. Default:false.
Enabling it also disables subscribing to channel groups, disables subscribing withWithPresence()(you can still subscribe to-pnpreschannels directly), and generates more server requests, which can increase costs. IncludeRequestIdentifier#- Whether the SDK adds a request identifier to requests. Default:
true. IncludeInstanceIdentifier#- Whether the SDK adds an instance identifier to requests. Default:
false. CryptoModule#- The cryptography module used for encryption and decryption of messages and files. Takes the
CipherKeyparameter as argument.
For more information, refer to the CryptoModule section. EnableEventEngine#- Default:
true. Whether to use the recommended standardized workflows for subscribe and presence, optimizing how the SDK internally handles these operations and which statuses it emits. MaintainPresenceState#- This option works only when
EnableEventEngineis set totrue.
Whether the custom presence state information set usingpubnub.setPresenceState()should be sent every time the SDK sends a subscribe call. Default:true. RetryConfiguration#- (When
EnableEventEngine = true) Custom reconnection configuration. SettingReconnectionPolicysets a default:RetryConfiguration.Linear(2, 10)forLINEARandRetryConfiguration.Exponential(2, 150, 6)forEXPONENTIAL. Options:RetryConfiguration.Linear(int delayInSecond, int maxRetry)RetryConfiguration.Exponential(int minDelayInSecond, int maxDelayInSecond, int maxRetry)
Deprecated#LogVerbosity- This parameter is deprecated, use
LogLevelinstead.SetPNLogVerbosity.BODYto enable debugging. To disable debugging use the optionPNLogVerbosity.NONE Deprecated#PubnubLog- This parameter is deprecated, use the
SetLoggermethod to configure a custom logger that implements theIPubnubLoggerinterface.Pass the instance of a class that implementsIPubnubLogto capture logs for troubleshooting. Deprecated#CipherKey- This way of setting this parameter is deprecated, pass it to
CryptoModuleinstead.
Ifcipheris passed, all communications to/from PubNub will be encrypted. Deprecated#UseRandomInitializationVector- This way of setting this parameter is deprecated, pass it to
CryptoModuleinstead.
Whentruethe IV will be random for all requests and not just file upload. Whenfalsethe IV will be hardcoded for all requests except File Upload. Defaulttrue. requiredDeprecated#Uuid- This parameter is deprecated, use
userIdinstead.UUIDto use. You should set a uniqueUUIDto identify the user or the device that connects to PubNub.
If you don't set theUUID, 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
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
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:
1
pnConfigurationrequired#- Go to Configuration for more details.
Sample code
Initialize the PubNub client API
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
Returns
Returns a PubNub instance for APIs like Publish(), Subscribe(), History(), and HereNow().
Other examples
Initialize a non-secure client
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 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:
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
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.
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
Requires Access Manager add-on
This method requires that the Access Manager add-on is enabled for your key in the Admin Portal. See Enable the features your app calls.
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:
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
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
Subscriptionobject can receive updates only for the particular object for which it was created: channel, channel group, channel metadata, or user. - The
SubscriptionsSetobject can receive updates for all objects for which a list of subscription objects was created.
To work with these sources, the SDK provides SDK entities, local handles for the objects a server holds, so you can subscribe and add handlers per entity. For details, see Publish & Subscribe.
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:
1
UserIdrequired#UserIdto be used as a device identifier. If you don't set theUserId, you won't be able to connect to PubNub.
1pubnub.GetCurrentUserId();
This method doesn't take any arguments.
Sample code
Set user ID
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
Get user ID
1
Authentication key
Set and get the user authentication key.
Property(s)
1pnConfiguration.AuthKey
AuthKey#- If Access Manager is utilized, client will use this
AuthKeyin all restricted requests.
This method doesn't take any arguments.
Sample code
Set auth key
1
Get auth key
1
Returns
Get Auth key returns the current authentication key.
Filter expression
Requires Stream Controller add-on
This method requires that the Stream Controller add-on is enabled for your key in the Admin Portal. See Enable the features your app calls.
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.
Property(s)
1FilterExpression
FilterExpression#- PSV2 feature to
Subscribewith a custom filter expression.
1pnConfiguration.FilterExpression;
This method doesn't take any arguments.
Sample code
Set filter expression
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
Get filter expression
1