Nethereum.JsonRpc.RpcClient 5.8.0

Prefix Reserved
dotnet add package Nethereum.JsonRpc.RpcClient --version 5.8.0
                    
NuGet\Install-Package Nethereum.JsonRpc.RpcClient -Version 5.8.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Nethereum.JsonRpc.RpcClient" Version="5.8.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Nethereum.JsonRpc.RpcClient" Version="5.8.0" />
                    
Directory.Packages.props
<PackageReference Include="Nethereum.JsonRpc.RpcClient" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Nethereum.JsonRpc.RpcClient --version 5.8.0
                    
#r "nuget: Nethereum.JsonRpc.RpcClient, 5.8.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Nethereum.JsonRpc.RpcClient@5.8.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Nethereum.JsonRpc.RpcClient&version=5.8.0
                    
Install as a Cake Addin
#tool nuget:?package=Nethereum.JsonRpc.RpcClient&version=5.8.0
                    
Install as a Cake Tool

Nethereum.JsonRpc.RpcClient

Production-ready HTTP/HTTPS JSON-RPC client for Ethereum node communication.

Overview

Nethereum.JsonRpc.RpcClient provides the standard HTTP/HTTPS transport implementation for communicating with Ethereum nodes via JSON-RPC. This is the most commonly used RPC client in Nethereum, offering robust connection management, automatic retries, authentication support, and production-tested reliability.

Key Features:

  • HTTP/HTTPS transport with HttpClient
  • Connection pooling and lifecycle management
  • Basic authentication support (username/password)
  • Configurable timeouts
  • Automatic HttpClient rotation (for older .NET versions)
  • Thread-safe concurrent requests
  • Production-tested reliability
  • Support for custom HttpClientHandler

Use Cases:

  • Connecting to Ethereum nodes (Geth, Erigon, Besu, Nethermind)
  • Querying blockchain data
  • Sending transactions
  • Contract interactions
  • Load balancer/proxy integration
  • Production dApp backends

Installation

dotnet add package Nethereum.JsonRpc.RpcClient

This is typically the default RPC client used by Nethereum.Web3:

dotnet add package Nethereum.Web3

Dependencies

Nethereum:

  • Nethereum.JsonRpc.Client - Core RPC abstraction (which provides JSON serialization support via Newtonsoft.Json or System.Text.Json)

Framework:

  • System.Net.Http - HTTP/HTTPS communication (built-in .NET library)

Quick Start

using Nethereum.JsonRpc.Client;
using Nethereum.RPC.Eth;

// Connect to local node
var client = new RpcClient(new Uri("http://localhost:8545"));

// Use with RPC services
var ethBlockNumber = new EthBlockNumber(client);
var blockNumber = await ethBlockNumber.SendRequestAsync();

Console.WriteLine($"Current block: {blockNumber.Value}");

Usage Examples

Example 1: Basic Connection to Ethereum Node

using Nethereum.JsonRpc.Client;
using Nethereum.RPC.Eth;
using Nethereum.Hex.HexTypes;

// Local Geth/Erigon/Besu node
var client = new RpcClient(new Uri("http://localhost:8545"));

// Infura
var infuraClient = new RpcClient(
    new Uri("https://mainnet.infura.io/v3/YOUR_PROJECT_ID")
);

// Alchemy
var alchemyClient = new RpcClient(
    new Uri("https://eth-mainnet.g.alchemy.com/v2/YOUR_API_KEY")
);

// Use with any RPC service
var ethChainId = new EthChainId(client);
HexBigInteger chainId = await ethChainId.SendRequestAsync();

Console.WriteLine($"Chain ID: {chainId.Value}");
// Output: Chain ID: 1 (mainnet)

Example 2: HTTP Basic Authentication

using Nethereum.JsonRpc.Client;
using System.Net.Http.Headers;
using System.Text;

// Option 1: URL-based authentication (simplest)
var client = new RpcClient(
    new Uri("http://username:password@localhost:8545")
);

// Option 2: Explicit AuthenticationHeaderValue
var credentials = Convert.ToBase64String(
    Encoding.UTF8.GetBytes("admin:secretpassword")
);
var authHeader = new AuthenticationHeaderValue("Basic", credentials);

var authenticatedClient = new RpcClient(
    new Uri("http://localhost:8545"),
    authHeaderValue: authHeader
);

// Use authenticated client
var ethAccounts = new EthAccounts(authenticatedClient);
var accounts = await ethAccounts.SendRequestAsync();

Console.WriteLine($"Accounts: {string.Join(", ", accounts)}");

Example 3: Custom Connection Timeout

using Nethereum.JsonRpc.Client;
using Nethereum.RPC.Eth;

var client = new RpcClient(new Uri("http://localhost:8545"));

// Default timeout is 120 seconds (2 minutes)
Console.WriteLine($"Default timeout: {client.ConnectionTimeout.TotalSeconds}s");

// Set custom timeout for slow networks
client.ConnectionTimeout = TimeSpan.FromSeconds(30);

try
{
    var ethGasPrice = new EthGasPrice(client);
    var gasPrice = await ethGasPrice.SendRequestAsync();
    Console.WriteLine($"Gas price: {gasPrice.Value} wei");
}
catch (RpcClientTimeoutException ex)
{
    Console.WriteLine($"Request timed out after 30 seconds: {ex.Message}");
}

Example 4: Using Custom HttpClient for Advanced Configuration

using Nethereum.JsonRpc.Client;
using System.Net.Http;

// Create custom HttpClient with specific settings
var httpClient = new HttpClient(new SocketsHttpHandler
{
    PooledConnectionLifetime = TimeSpan.FromMinutes(15),
    PooledConnectionIdleTimeout = TimeSpan.FromMinutes(10),
    MaxConnectionsPerServer = 50,
    EnableMultipleHttp2Connections = true
})
{
    Timeout = TimeSpan.FromSeconds(60)
};

// Create RpcClient with custom HttpClient
var client = new RpcClient(
    new Uri("http://localhost:8545"),
    httpClient: httpClient
);

var ethBlockNumber = new EthBlockNumber(client);
var blockNumber = await ethBlockNumber.SendRequestAsync();

Console.WriteLine($"Block: {blockNumber.Value}");

Example 5: Custom HttpClientHandler for Proxy Support

using Nethereum.JsonRpc.Client;
using System.Net;
using System.Net.Http;

// Configure proxy
var handler = new HttpClientHandler
{
    Proxy = new WebProxy("http://proxy.example.com:8080")
    {
        Credentials = new NetworkCredential("proxyuser", "proxypass")
    },
    UseProxy = true,
    MaxConnectionsPerServer = 20
};

// Create client with proxy handler
var client = new RpcClient(
    new Uri("http://localhost:8545"),
    httpClientHandler: handler
);

var ethChainId = new EthChainId(client);
var chainId = await ethChainId.SendRequestAsync();

Console.WriteLine($"Chain ID (via proxy): {chainId.Value}");

Example 6: Multiple Concurrent Requests (Thread Safety)

using Nethereum.JsonRpc.Client;
using Nethereum.RPC.Eth.DTOs;
using System.Threading.Tasks;

var client = new RpcClient(new Uri("http://localhost:8545"));

// RpcClient is thread-safe - can handle concurrent requests
var tasks = new List<Task>
{
    Task.Run(async () =>
    {
        var ethBlockNumber = new EthBlockNumber(client);
        var block = await ethBlockNumber.SendRequestAsync();
        Console.WriteLine($"Task 1 - Block: {block.Value}");
    }),

    Task.Run(async () =>
    {
        var ethGasPrice = new EthGasPrice(client);
        var gasPrice = await ethGasPrice.SendRequestAsync();
        Console.WriteLine($"Task 2 - Gas Price: {gasPrice.Value}");
    }),

    Task.Run(async () =>
    {
        var ethChainId = new EthChainId(client);
        var chainId = await ethChainId.SendRequestAsync();
        Console.WriteLine($"Task 3 - Chain ID: {chainId.Value}");
    })
};

await Task.WhenAll(tasks);
Console.WriteLine("All requests completed successfully");

Example 7: Error Handling and Retry Logic

using Nethereum.JsonRpc.Client;
using Nethereum.RPC.Eth;
using Polly;

var client = new RpcClient(new Uri("http://localhost:8545"));
client.ConnectionTimeout = TimeSpan.FromSeconds(10);

// Define retry policy with Polly
var retryPolicy = Policy
    .Handle<RpcClientTimeoutException>()
    .Or<RpcClientUnknownException>()
    .WaitAndRetryAsync(
        retryCount: 3,
        sleepDurationProvider: attempt => TimeSpan.FromSeconds(Math.Pow(2, attempt)),
        onRetry: (exception, timeSpan, retryCount, context) =>
        {
            Console.WriteLine($"Retry {retryCount} after {timeSpan.TotalSeconds}s due to: {exception.Message}");
        }
    );

try
{
    var blockNumber = await retryPolicy.ExecuteAsync(async () =>
    {
        var ethBlockNumber = new EthBlockNumber(client);
        return await ethBlockNumber.SendRequestAsync();
    });

    Console.WriteLine($"Success! Block: {blockNumber.Value}");
}
catch (RpcResponseException ex)
{
    Console.WriteLine($"RPC Error {ex.RpcError.Code}: {ex.RpcError.Message}");
}
catch (RpcClientTimeoutException ex)
{
    Console.WriteLine($"Timeout after retries: {ex.Message}");
}
catch (RpcClientUnknownException ex)
{
    Console.WriteLine($"Network error: {ex.Message}");
}

Example 8: Load Balancing Across Multiple Nodes

using Nethereum.JsonRpc.Client;
using Nethereum.RPC.Eth;

public class LoadBalancedRpcClient
{
    private readonly List<RpcClient> _clients;
    private int _currentIndex = 0;
    private readonly object _lock = new object();

    public LoadBalancedRpcClient(params string[] nodeUrls)
    {
        _clients = nodeUrls.Select(url => new RpcClient(new Uri(url))).ToList();
    }

    public RpcClient GetNextClient()
    {
        lock (_lock)
        {
            var client = _clients[_currentIndex];
            _currentIndex = (_currentIndex + 1) % _clients.Count;
            return client;
        }
    }
}

// Usage
var loadBalancer = new LoadBalancedRpcClient(
    "http://node1.example.com:8545",
    "http://node2.example.com:8545",
    "http://node3.example.com:8545"
);

// Round-robin requests
for (int i = 0; i < 10; i++)
{
    var client = loadBalancer.GetNextClient();
    var ethBlockNumber = new EthBlockNumber(client);
    var block = await ethBlockNumber.SendRequestAsync();
    Console.WriteLine($"Request {i + 1} - Block: {block.Value}");
}

Example 9: Using with Nethereum.Web3

using Nethereum.Web3;
using Nethereum.JsonRpc.Client;

// Option 1: Web3 creates RpcClient internally (simplest)
var web3 = new Web3("https://mainnet.infura.io/v3/YOUR_PROJECT_ID");

// Option 2: Create custom RpcClient first
var client = new RpcClient(new Uri("http://localhost:8545"));
client.ConnectionTimeout = TimeSpan.FromSeconds(60);

var web3WithCustomClient = new Web3(client);

// Use Web3 normally
var balance = await web3WithCustomClient.Eth.GetBalance.SendRequestAsync("0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb");
Console.WriteLine($"Balance: {Web3.Convert.FromWei(balance)} ETH");

var blockNumber = await web3WithCustomClient.Eth.Blocks.GetBlockNumber.SendRequestAsync();
Console.WriteLine($"Block: {blockNumber.Value}");

API Reference

RpcClient Constructor Overloads

// Basic constructor
public RpcClient(Uri baseUrl,
    AuthenticationHeaderValue authHeaderValue = null,
    JsonSerializerSettings jsonSerializerSettings = null,
    HttpClientHandler httpClientHandler = null,
    ILogger log = null)

// With custom HttpClient
public RpcClient(Uri baseUrl,
    HttpClient httpClient,
    AuthenticationHeaderValue authHeaderValue = null,
    JsonSerializerSettings jsonSerializerSettings = null,
    ILogger log = null)

Properties

public static int MaximumConnectionsPerServer { get; set; } = 20;
public TimeSpan ConnectionTimeout { get; set; } // Default: 120 seconds
public RequestInterceptor OverridingRequestInterceptor { get; set; }

Key Methods (Inherited from ClientBase)

Task<T> SendRequestAsync<T>(RpcRequest request, string route = null);
Task<T> SendRequestAsync<T>(string method, string route = null, params object[] paramList);
Task<RpcRequestResponseBatch> SendBatchRequestAsync(RpcRequestResponseBatch batch);
Task<RpcResponseMessage> SendAsync(RpcRequestMessage request, string route = null);

Important Notes

Connection Management

HttpClient Rotation:

  • On older .NET Framework, RpcClient automatically rotates HttpClient instances every 60 seconds
  • On .NET Core 2.1+, uses SocketsHttpHandler with connection pooling
  • Connection lifetime: 10 minutes
  • Idle timeout: 5 minutes
  • Max connections per server: 20 (configurable via MaximumConnectionsPerServer)

Best Practices:

  • Reuse RpcClient instances (don't create per request)
  • Set appropriate timeouts based on network conditions
  • Use connection pooling for high-traffic applications

Thread Safety

  • Thread-safe after initialization
  • Safe to call from multiple threads concurrently
  • Connection pooling handles concurrent requests efficiently
  • Lock-free for read operations

Performance

Operation Latency Notes
Local node 1-10ms Localhost Geth/Erigon
Cloud provider 50-200ms Infura, Alchemy, QuickNode
Slow network 200-500ms High latency regions

Optimization Tips:

  • Enable HTTP/2 with EnableMultipleHttp2Connections
  • Use batch requests for multiple calls
  • Tune MaxConnectionsPerServer for high throughput
  • Consider WebSocket client for subscriptions

Error Handling

Exception Cause Retry?
RpcClientTimeoutException Request exceeded ConnectionTimeout Yes (with backoff)
RpcClientUnknownException Network/HTTP errors Yes (transient)
RpcResponseException JSON-RPC error from node Depends on error code
HttpRequestException DNS, connection failures Yes (with backoff)

Authentication

Supports HTTP Basic Authentication:

  • URL-based: http://user:pass@localhost:8545
  • Header-based: AuthenticationHeaderValue("Basic", base64Credentials)
  • Automatically extracted from URI if present

JSON Serialization

Uses Newtonsoft.Json with default settings optimized for Ethereum:

  • Proper handling of 0x hex prefixes
  • BigInteger serialization
  • Block/transaction DTOs

For System.Text.Json, use Nethereum.JsonRpc.SystemTextJsonRpcClient instead.

Logging

Supports Microsoft.Extensions.Logging:

var loggerFactory = LoggerFactory.Create(builder => builder.AddConsole());
var logger = loggerFactory.CreateLogger<RpcClient>();

var client = new RpcClient(
    new Uri("http://localhost:8545"),
    log: logger
);

Logs include:

  • Request JSON payloads
  • Response JSON payloads
  • Exception details
  • Performance metrics

Alternative Transports

  • Nethereum.JsonRpc.SystemTextJsonRpcClient - HTTP with System.Text.Json
  • Nethereum.JsonRpc.WebSocketClient - WebSocket transport
  • Nethereum.JsonRpc.IpcClient - IPC transport (Unix sockets, named pipes)

Higher-Level APIs

  • Nethereum.Web3 - Complete Web3 API (uses RpcClient internally)
  • Nethereum.RPC - Typed RPC services

Core Dependencies

  • Nethereum.JsonRpc.Client - Abstraction layer

Common Ethereum Node Providers

Provider URL Format Notes
Infura https://mainnet.infura.io/v3/PROJECT_ID Free tier available
Alchemy https://eth-mainnet.g.alchemy.com/v2/API_KEY Enhanced APIs
QuickNode https://your-endpoint.quiknode.pro/token/ Global network
Local Geth http://localhost:8545 Full node
Local Erigon http://localhost:8545 Archive node

Additional Resources

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net451 is compatible.  net452 was computed.  net46 was computed.  net461 is compatible.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (14)

Showing the top 5 NuGet packages that depend on Nethereum.JsonRpc.RpcClient:

Package Downloads
Nethereum.Web3

Nethereum.Web3 Ethereum Web3 Class Library to interact via RPC with an Ethereum client, for example geth. Including contract interaction, deployment, transaction, encoding / decoding and event filters

Nethereum.BlockchainProcessing

Nethereum.BlockchainProcessing Ethereum blockchain processing allowing to crawl Blocks, Transactions, TransactionReceipts and Logs (Event) for storage and / or using custom handlers like queuing , search, etc

Nethereum.Web3Lite

Nethereum.Web3Lite Ethereum Web3 Class Library (light browser version, with no reference to signing crypto libraries) to interact via RPC with an Ethereum client, for example geth. Including contract interaction, deployment, transaction, encoding / decoding and event filters

Aoite.Neth

The aoite ethereum module.

WalletConnect.NEthereum

An NEthereum extension to access the WalletConnect protocol through a Web3 Provider. A lightweight C# implementation of the WalletConnect protocol that can be used to connect to external wallets or connect a wallet to an external Dapp

GitHub repositories (4)

Showing the top 4 popular GitHub repositories that depend on Nethereum.JsonRpc.RpcClient:

Repository Stars
yc-l/yc.boilerplate
YC. Boilerplate is a set of loose coupling, flexible combination, complete functions, convenient development, and reduces the workload of development.
unoplatform/Uno.Samples
A collection of code samples for the Uno Platform
JayArrowz/PancakeTokenSniper
BSC BNB Pancake token sniper, buy, take profit and rug check
biheBlockChain/MyLinkToken
开源链克口袋,玩客币钱包
Version Downloads Last Updated
5.8.0 0 1/6/2026
5.0.0 291,696 5/28/2025
4.29.0 209,279 2/10/2025
4.28.0 61,800 1/7/2025
4.27.1 12,431 12/24/2024
4.27.0 1,573 12/24/2024
4.26.0 95,999 10/1/2024
4.25.0 22,543 9/19/2024
4.21.4 96,059 8/9/2024
4.21.3 11,273 7/22/2024
4.21.2 67,838 6/26/2024
4.21.1 2,579 6/26/2024
4.21.0 10,377 6/18/2024
4.20.0 314,861 3/28/2024
4.19.0 64,891 2/16/2024
4.18.0 270,480 11/21/2023
4.17.1 77,889 9/28/2023
4.17.0 17,180 9/27/2023
4.16.0 117,591 8/14/2023
4.15.2 123,375 7/11/2023
4.15.1 4,146 7/11/2023
4.15.0 4,648 7/11/2023
4.14.0 188,962 3/19/2023
4.13.0 130,652 2/18/2023
4.12.0 268,337 12/9/2022
4.11.0 174,156 10/27/2022
4.9.0 111,638 9/27/2022
4.8.0 177,898 8/24/2022
4.7.0 148,244 7/20/2022
4.6.1 129,409 6/18/2022
4.6.0 9,366 6/16/2022
4.5.0 389,074 5/13/2022
4.4.1 104,666 4/27/2022
4.4.0 13,069 4/27/2022
4.3.0 64,650 4/12/2022
4.2.0 169,957 2/18/2022
4.1.1 491,696 11/4/2021
4.1.0 29,398 10/15/2021
4.0.5 140,863 8/12/2021
4.0.4 7,741 8/10/2021
4.0.3 7,596 8/8/2021
4.0.2 6,832 8/5/2021
4.0.1 12,416 7/28/2021
4.0.0 18,037 7/26/2021
3.8.0 391,508 7/3/2020
3.7.1 116,474 2/13/2020
3.7.0 9,545 2/13/2020
3.6.0 32,882 1/27/2020
3.5.0 20,318 12/31/2019
3.4.0 147,461 7/29/2019
3.3.0 73,596 4/23/2019
3.2.0 43,400 4/8/2019
3.1.2 22,607 3/13/2019
3.1.1 5,376 3/12/2019
3.1.0 26,304 3/12/2019
3.0.0 37,106 11/28/2018
3.0.0-rc3 5,822 10/25/2018
3.0.0-rc2 3,512 10/24/2018
3.0.0-rc1 9,196 7/25/2018
2.5.1 105,142 6/5/2018
2.5.0 5,918 6/4/2018
2.4.0 52,682 3/11/2018
2.3.1 7,700 3/7/2018
2.3.0 6,195 3/6/2018
2.2.3 18,773 12/16/2017
2.2.2 6,127 12/16/2017
2.2.0 6,317 12/8/2017
2.1.0 12,126 10/23/2017
2.0.1 6,129 10/4/2017
2.0.0 6,776 9/26/2017
2.0.0-rc7 4,418 8/17/2017
2.0.0-rc6-2 4,026 7/29/2017
2.0.0-rc6.1 1,019 7/26/2017
2.0.0-rc5 3,019 6/19/2017
2.0.0-rc4 4,120 6/6/2017
2.0.0-rc3 3,684 4/11/2017
2.0.0-rc2-fix 3,231 4/6/2017
2.0.0-rc2 2,038 4/5/2017