Class CloudflareApiClient
- Namespace
- Cloudflare.NET
- Assembly
- Cloudflare.NET.dll
The primary client for interacting with the Cloudflare API.
public sealed class CloudflareApiClient : ICloudflareApiClient, IDisposable
- Inheritance
-
CloudflareApiClient
- Implements
- Inherited Members
Constructors
CloudflareApiClient(HttpClient, IOptions<CloudflareApiOptions>, ILoggerFactory)
Initializes a new instance of the Cloudflare API client.
public CloudflareApiClient(HttpClient httpClient, IOptions<CloudflareApiOptions> options, ILoggerFactory loggerFactory)
Parameters
httpClientHttpClientThe HttpClient to be used for all API calls.
optionsIOptions<CloudflareApiOptions>The Cloudflare API options.
loggerFactoryILoggerFactoryThe factory to create loggers for API resources.
Properties
Accounts
Gets the API resource for managing Account-level resources. This includes R2 buckets, account-wide IP Access Rules, and account-level WAF custom rulesets.
public IAccountsApi Accounts { get; }
Property Value
ApiTokens
Gets the API resource for managing API tokens.
API tokens provide fine-grained access control for Cloudflare API operations. Each token has policies that define what resources and actions are allowed.
public IApiTokensApi ApiTokens { get; }
Property Value
Examples
// Create a new token
var result = await cf.ApiTokens.CreateAccountTokenAsync(accountId,
new CreateApiTokenRequest(
Name: "CI/CD Token",
Policies: new[]
{
new CreateTokenPolicyRequest(
Effect: "allow",
PermissionGroups: new[] { new TokenPermissionGroupReference(permGroupId) },
Resources: new Dictionary<string, string>
{
["com.cloudflare.api.account.*"] = "*"
})
}));
Console.WriteLine($"Token: {result.Value}"); // Store securely!
AuditLogs
Gets the API resource for accessing audit logs.
Audit logs provide a record of actions taken on account resources, useful for security monitoring, compliance, and troubleshooting. Logs are retained for 30 days.
public IAuditLogsApi AuditLogs { get; }
Property Value
Examples
// Get recent audit logs
var logs = await cf.AuditLogs.GetAccountAuditLogsAsync(accountId,
new ListAuditLogsFilters(Since: DateTime.UtcNow.AddDays(-7)));
foreach (var log in logs.Items)
{
Console.WriteLine($"{log.Action.Time}: {log.Action.Type} by {log.Actor.Email}");
}
Dns
Gets the API resource for managing DNS records.
Provides complete CRUD operations for DNS records, including batch operations, import/export functionality, and searching by hostname.
public IDnsApi Dns { get; }
Property Value
Examples
// Create a DNS record
var record = await cf.Dns.CreateDnsRecordAsync(zoneId, new CreateDnsRecordRequest(
DnsRecordType.A, "www.example.com", "192.0.2.1"
));
// List all DNS records
await foreach (var r in cf.Dns.ListAllDnsRecordsAsync(zoneId))
{
Console.WriteLine($"{r.Name}: {r.Content}");
}
Members
Gets the API resource for managing account members.
Account members are users who have been granted access to a Cloudflare account. Members are assigned roles that determine their permissions within the account.
public IMembersApi Members { get; }
Property Value
Examples
// List all account members
await foreach (var member in cf.Members.ListAllAccountMembersAsync(accountId))
{
Console.WriteLine($"{member.User.Email}: {member.Status}");
foreach (var role in member.Roles)
Console.WriteLine($" - {role.Name}");
}
// Invite a new member
var newMember = await cf.Members.CreateAccountMemberAsync(accountId,
new CreateAccountMemberRequest(
Email: "[email protected]",
Roles: new[] { adminRoleId },
Status: MemberStatus.Pending));
Roles
Gets the API resource for managing account roles.
Roles are predefined by Cloudflare and define sets of permissions that can be assigned to account members. This API is read-only.
public IRolesApi Roles { get; }
Property Value
Examples
// List all available roles
await foreach (var role in cf.Roles.ListAllAccountRolesAsync(accountId))
{
Console.WriteLine($"{role.Name}: {role.Description}");
if (role.Permissions.Dns?.Write == true)
Console.WriteLine(" - Can modify DNS");
}
Subscriptions
Gets the API resource for managing subscriptions.
Subscriptions manage billing plans and add-ons for Cloudflare services. This API provides access to account-level subscription management.
public ISubscriptionsApi Subscriptions { get; }
Property Value
Examples
// List account subscriptions
var subscriptions = await cf.Subscriptions.ListAccountSubscriptionsAsync(accountId);
foreach (var sub in subscriptions)
{
Console.WriteLine($"{sub.RatePlan?.PublicName}: {sub.State}");
Console.WriteLine($" Price: {sub.Price} {sub.Currency}/{sub.Frequency}");
}
// Create a new subscription
var newSub = await cf.Subscriptions.CreateAccountSubscriptionAsync(accountId,
new CreateAccountSubscriptionRequest(
RatePlan: new RatePlanReference("rate_plan_id"),
Frequency: SubscriptionFrequency.Monthly));
Remarks
Billing Permissions Required: Requires tokens with Billing Read/Write permissions.
Cost Warning: Creating or updating subscriptions may incur charges.
Turnstile
Gets the API resource for managing Turnstile widgets.
Turnstile is Cloudflare's CAPTCHA alternative that provides bot protection without user friction. Widgets are account-scoped resources.
public ITurnstileApi Turnstile { get; }
Property Value
Examples
// Create a Turnstile widget
var widget = await cf.Turnstile.CreateWidgetAsync(accountId,
new CreateTurnstileWidgetRequest(
Name: "Contact Form",
Domains: new[] { "example.com" },
Mode: WidgetMode.Managed));
// IMPORTANT: Store the secret securely - it won't be available again!
Console.WriteLine($"Sitekey: {widget.Sitekey}");
Console.WriteLine($"Secret: {widget.Secret}");
// Later, rotate the secret
var result = await cf.Turnstile.RotateSecretAsync(accountId, widget.Sitekey);
Console.WriteLine($"New secret: {result.Secret}");
Remarks
Important: Widget secrets are only returned on creation and rotation. Store them securely as they cannot be retrieved again.
User
Gets the API resource for managing the authenticated user's profile.
This includes retrieving and editing the current user's personal information, such as name, country, and contact details.
public IUserApi User { get; }
Property Value
Workers
Gets the API resource for managing Worker routes.
Worker routes map URL patterns to Worker scripts, determining which requests are handled by which Workers. Routes are zone-scoped resources.
public IWorkersApi Workers { get; }
Property Value
Examples
// List all Worker routes in a zone
var routes = await cf.Workers.ListRoutesAsync(zoneId);
foreach (var route in routes)
{
Console.WriteLine($"{route.Pattern} -> {route.Script ?? "(disabled)"}");
}
// Create a new route
var newRoute = await cf.Workers.CreateRouteAsync(zoneId,
new CreateWorkerRouteRequest(
Pattern: "api.example.com/*",
Script: "api-handler"));
Zones
Gets the API resource for managing Zone-level resources. This includes DNS records, zone-specific IP Access Rules, WAF configurations, and other settings scoped to a specific zone.
public IZonesApi Zones { get; }
Property Value
Methods
Dispose()
Disposes this client instance.
public void Dispose()
Remarks
For DI-managed clients, this method does nothing because the HttpClient lifetime is managed by IHttpClientFactory. The factory handles pooling and disposal of the underlying handlers automatically.
For dynamic clients created via CreateClient(CloudflareApiOptions), the Cloudflare.NET.Core.DynamicCloudflareApiClient wrapper handles actual disposal of resources.