AlphaQuantum.CipaWebFiltering
1.0.0
dotnet add package AlphaQuantum.CipaWebFiltering --version 1.0.0
NuGet\Install-Package AlphaQuantum.CipaWebFiltering -Version 1.0.0
<PackageReference Include="AlphaQuantum.CipaWebFiltering" Version="1.0.0" />
<PackageVersion Include="AlphaQuantum.CipaWebFiltering" Version="1.0.0" />
<PackageReference Include="AlphaQuantum.CipaWebFiltering" />
paket add AlphaQuantum.CipaWebFiltering --version 1.0.0
#r "nuget: AlphaQuantum.CipaWebFiltering, 1.0.0"
#:package AlphaQuantum.CipaWebFiltering@1.0.0
#addin nuget:?package=AlphaQuantum.CipaWebFiltering&version=1.0.0
#tool nuget:?package=AlphaQuantum.CipaWebFiltering&version=1.0.0
AlphaQuantum.CipaWebFiltering
.NET 8 client for the CIPA Web Filtering lookup API. It returns the web-filtering categories of any domain, single or in batches of 1,000, and includes a Policy class that evaluates those categories the way school and library filters do.
dotnet add package AlphaQuantum.CipaWebFiltering
The package targets net8.0, uses only System.Net.Http and System.Text.Json, and ships XML documentation for IntelliSense. Background on the platform is on learn.microsoft.com; the package page is on nuget.org.
Written for Windows-heavy district IT
A lot of US school districts run on Microsoft: Active Directory or Entra ID, Intune for devices, a few Windows servers, PowerShell for everything that repeats. The filtering appliance or service sits beside that stack, and the questions about it come to the same small team:
- Which categories did students reach last month, by school?
- Is this site blocked, and why?
- Can we produce a record for our E-Rate file showing the filter was in place and what it blocked?
- If we change the policy, what breaks?
This package lets you answer those from C# services, scheduled tasks and PowerShell scripts, with the same category data that powers a hosted cipa compliant web filter. It does not replace your filter; it gives your own tooling the data and the decision logic.
Getting started
using CipaWebFiltering;
using var client = new CipaWebFilteringClient(Environment.GetEnvironmentVariable("CWF_API_KEY")!);
var r = await client.ClassifyAsync("teams.microsoft.com");
Console.WriteLine($"{r.Domain}: {string.Join(", ", r.Categories)}");
Console.WriteLine($"found={r.Found} method={r.Method} country={r.Country ?? "unknown"}");
ClassifyAsync accepts a domain, hostname or URL and costs one credit. The result is a Classification record:
public sealed record Classification(
string Domain, // as the service saw it
string? RootDomain, // registrable domain that matched
IReadOnlyList<string> Categories, // web-filtering categories, no particular order
string? ContentCategory, // broader content label, if any
string? Country, // null when unknown; placeholders like "-" are removed
string Method, // "not_found" when there is no record
double Confidence) // 1.0 for a direct record
{
public bool Found { get; } // true when at least one category exists
}
CipaWebFilteringClient is thread-safe. Register one instance as a singleton, or pass your own HttpClient (for example one created by IHttpClientFactory) through the third constructor parameter:
builder.Services.AddHttpClient("cwf");
builder.Services.AddSingleton(sp =>
new CipaWebFilteringClient(
builder.Configuration["Cwf:ApiKey"]!,
http: sp.GetRequiredService<IHttpClientFactory>().CreateClient("cwf")));
When you pass an HttpClient, the client does not dispose it, so its lifetime stays with the factory that created it.
Batches
var (results, credits) = await client.ClassifyManyAsync(domains);
Console.WriteLine($"{results.Count} classified, {credits?.Remaining} credits left");
ClassifyManyAsync trims and drops empty entries, splits the input into chunks of CipaWebFilteringClient.BatchMax (1,000) and posts each chunk. The returned Credits (UsedThisRequest, Remaining, Total) come from the last chunk. If a chunk would exceed the remaining credits, the service answers 429 before doing any work and the call throws CipaApiException with Status == 429.
Policies
var policy = Policy.District();
bool blocked = policy.Blocks(r.Categories.ToList());
IReadOnlyList<string> because = policy.Matches(r.Categories);
Policy holds a set of blocked categories and a BlockRule:
| Rule | Behaviour on a site with several categories |
|---|---|
BlockRule.Any |
blocked if any category is in the policy |
BlockRule.Majority |
blocked if more than half are |
BlockRule.All |
blocked only if all are |
Five static factories build cumulative presets, and the category arrays are public so you can compose your own:
| Factory | Adds |
|---|---|
Policy.StatutoryCoreOnly() |
Adult |
Policy.WithCircumvention() |
VPN / Proxy / Anonymizers |
Policy.BroadHarmSet() |
Lingerie/Swimsuits/Intimate Apparel, Violence, Weapons, Hate/Discrimination, Illegal Drugs, Gambling |
Policy.District() |
Alcohol, Tobacco, Dating, File Sharing/P2P, Remote Access Tools, URL Shorteners, Parked / For-Sale Domains, Cryptocurrency, Phishing / Suspicious |
Policy.Restrictive() |
Social Networking, Gaming, Streaming Media, Forums, Community Sites, Shopping, Marketplaces, Podcasts, Sports & Recreation, AI / LLM Tools, Email and Messaging, Blogs |
var mine = new Policy(Policy.StatutoryCore.Concat(Policy.Circumvention).Append("Gaming"), BlockRule.Any);
var lenient = Policy.Restrictive().WithRule(BlockRule.Majority);
Choosing a rule with numbers, not instinct
An October 2026 simulation evaluated these exact presets over 103 million categorised domains and counted how many of the 16.3 million domains carrying an education, health, government, news, science or civic label each one blocked. Under Any:
| Preset | Domains blocked | Protected-label domains blocked |
|---|---|---|
| Statutory core | 0.92% | 0.048% |
| + circumvention | 0.93% | 0.049% |
| Broad harm set | 3.36% | 0.17% |
| Typical district | 4.59% | 0.30% |
| Restrictive | 19.1% | 7.6% |
The restrictive preset also blocked 2.2% of .edu, 1.7% of US K-12 and 4.2% of government domains, nearly all through Sports & Recreation, Shopping and Community Sites labels. With Majority instead of Any, its collateral dropped by about 94%. The advice that follows: keep the statutory core and circumvention on Any, and evaluate discretionary categories with a separate, lenient policy.
PowerShell
The package is a plain .NET assembly, so PowerShell 7 can load it directly. After dotnet add package in any project, the DLL is in your NuGet cache; or download the .nupkg from nuget.org and extract it.
Add-Type -Path "$HOME/.nuget/packages/alphaquantum.cipawebfiltering/1.0.0/lib/net8.0/CipaWebFiltering.dll"
$client = [CipaWebFiltering.CipaWebFilteringClient]::new($env:CWF_API_KEY, $null, $null)
$r = $client.ClassifyAsync("roblox.com", [Threading.CancellationToken]::None).GetAwaiter().GetResult()
"{0}: {1}" -f $r.Domain, ($r.Categories -join ", ")
$policy = [CipaWebFiltering.Policy]::District()
$policy.Blocks([string[]]$r.Categories)
A typical scheduled script reads yesterday's DNS or proxy log, takes the distinct hosts, classifies them in one batch and writes a CSV per school:
$hosts = Import-Csv .\dns-yesterday.csv | Select-Object -ExpandProperty host -Unique
$res = $client.ClassifyManyAsync([string[]]$hosts, [Threading.CancellationToken]::None).GetAwaiter().GetResult()
$res.Item1 | ForEach-Object {
[pscustomobject]@{ Domain = $_.Domain; Categories = ($_.Categories -join "|"); Found = $_.Found }
} | Export-Csv .\categories-yesterday.csv -NoTypeInformation
A lookup endpoint for your help desk
Help-desk staff should not need an API key or a console. A tiny ASP.NET minimal API in front of the client gives them a URL they can bookmark, and keeps the key on the server:
var app = builder.Build();
var floor = Policy.WithCircumvention();
var lessons = Policy.Restrictive().WithRule(BlockRule.Majority);
app.MapGet("/check", async (string site, CipaWebFilteringClient cwf, CancellationToken ct) =>
{
var r = await cwf.ClassifyAsync(site, ct);
return Results.Ok(new
{
r.Domain,
r.Categories,
r.Found,
blockedAlways = floor.Matches(r.Categories),
limitedInLessons = lessons.Blocks(r.Categories.ToList()) ? lessons.Matches(r.Categories) : Array.Empty<string>(),
});
});
app.Run();
Put it behind your single sign-on and it becomes the first place staff look before opening a ticket. Logging each request (who asked, which site, what the answer was) also tells you which sites cause the most friction, which is useful input for the next policy review.
Keeping the policy in configuration
Hard-coding category lists in C# means a release every time the board changes its mind. Bind them from appsettings.json instead:
{
"Cwf": {
"ApiKey": "set in user secrets or the environment",
"Discretionary": { "Rule": "Majority", "Categories": [ "Gaming", "Social Networking", "Streaming Media" ] }
}
}
var section = builder.Configuration.GetSection("Cwf:Discretionary");
var discretionary = new Policy(
section.GetSection("Categories").Get<string[]>() ?? Array.Empty<string>(),
Enum.Parse<BlockRule>(section["Rule"] ?? "Any"));
Keep the statutory floor in code and the discretionary part in configuration. That split mirrors the law: the floor is not negotiable, everything else is a local decision that changes from year to year.
Building an audit record
Every district that takes E-Rate money files a CIPA certification and must be able to show that a technology protection measure was in place and what its Internet Safety Policy says. There is no product-level cipa certification; the certification is the institution's own statement. What auditors like to see is evidence that the stated policy matches what the filter did.
A small console job can produce that evidence monthly:
var policy = Policy.District();
var lines = new List<string> { "domain,categories,blocked,because" };
foreach (var r in results)
{
var hits = policy.Matches(r.Categories);
lines.Add($"{r.Domain},\"{string.Join("|", r.Categories)}\",{(hits.Count > 0 ? "yes" : "no")},\"{string.Join("|", hits)}\"");
}
await File.WriteAllLinesAsync($"cipa-evidence-{DateTime.UtcNow:yyyy-MM}.csv", lines);
Store the policy definition (the category list and rule) next to the CSV. Months later, that pair answers "why was this site blocked in March?" without anyone having to remember.
Intune and managed devices
DNS-level filtering only covers traffic that uses the district's resolver. Windows devices that leave the building need a policy that keeps them on it, which is configured in Intune, not in code. Where this package helps is in the reporting loop: classify the domains that devices actually reach (from your resolver or proxy logs) and compare them with the categories your policy blocks, school by school. Districts organising that per level will find the notes on k12 content filtering a practical template, and those moving the resolver out of their own data centre usually start from cloud based internet filtering.
A short history, for the README readers who ask
CIPA was enacted in December 2000 as part of an appropriations act, and the FCC's rules took effect in 2001. The Supreme Court upheld the library provisions in 2003. Since 2011, schools' Internet Safety Policies must also cover educating students about appropriate online behaviour. If you need the full answer to when was cipa passed and what changed since, the site keeps a plain-English summary. The part that matters for software has not changed: the law names three kinds of content, and everything else is local policy.
Errors
try
{
var r = await client.ClassifyAsync(domain, ct);
}
catch (CipaApiException e) when (e.Status == 401) { /* key missing or invalid */ }
catch (CipaApiException e) when (e.Status == 429) { /* not enough credits */ }
catch (CipaApiException e) when (e.Status == 502) { /* backend briefly unavailable, retry later */ }
catch (HttpRequestException) { /* network */ }
catch (TaskCanceledException) { /* timeout or cancellation */ }
The default timeout is 60 seconds, which suits batches. For interactive lookups, pass a CancellationToken with a shorter deadline. The client never retries on its own, so a lost batch response is not charged twice.
Health and account endpoints
JsonElement health = await client.HealthAsync(); // free, no key needed
JsonElement status = await client.AccountStatusAsync(); // database subscribers: key and plan
JsonElement info = await client.DatabaseInfoAsync(); // last update time and file size
Use HealthAsync in a health-check endpoint (app.MapHealthChecks) or as the first step of a scheduled task. It costs nothing, needs no key, and tells you whether a failed nightly job was your network or the service.
Testing
The client accepts an HttpClient, so tests can supply one with a stub HttpMessageHandler and no network. The package's own tests do this for single lookups, batches, credits and a 401 from a wrong key. For your own code, keep policies in configuration and test them against fixed Classification instances:
var fixture = new Classification("example.org", "example.org", new[] { "Shopping", "Weapons" }, null, null, "root_domain_direct", 1);
Assert.True(Policy.BroadHarmSet().Blocks(fixture.Categories.ToList()));
Assert.False(Policy.BroadHarmSet().WithRule(BlockRule.Majority).Blocks(fixture.Categories.ToList()));
FAQ
Is this a filter? No. It is the data and decision layer. The network still needs a resolver, proxy or firewall that enforces the answer, or a hosted school web filter that does it for you.
How does it compare to a full product? A full product adds enforcement, reporting, device agents and support. The overview of the best internet filtering software for schools explains what each piece does if you are deciding what to build yourself.
Why are categories not ordered? Because the service does not rank them. Treat them as a set.
Can I run it from Azure Functions or a Windows service? Yes. It has no static state and no dependency on ASP.NET, so it runs in any .NET 8 host. In serverless hosts, keep one client per instance rather than one per invocation, so connections are reused.
How many credits will a district use? Classify distinct domains, not requests. A district's daily logs often hold millions of requests but only tens of thousands of distinct domains, and with a cache of a day most of those are already known.
What about sites the database does not know? Found is false and Categories is empty; no policy blocks them. Decide explicitly how your tool treats unknown sites.
License
MIT, Copyright (c) 2026 Alpha Quantum.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | 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 was computed. 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. |
-
net8.0
- No dependencies.
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 1.0.0 | 114 | 10/19/2026 |