Curl DotNet:为.NET 运行时带来 Curl 超强功能
对于每个 .NET 开发人员来说,这样的场景再熟悉不过了:您正在阅读一个新 API 的文档,而提供者给了您一个 curl 命令来测试一个端点。 您盯着命令行工具语法,叹了口气,然后开始将其翻译成 C# 中新的 HttpClient 实例的繁琐过程。
您必须手动映射标题,确保正文的字符串值编码正确,处理用户代理,并希望您没有遗漏默许默认值。 这种手动 bash 复制和翻译过程很容易出错。 缺少一个标头,您的 HTTP 请求就会失败。
输入 CurlDotNet。 由 Iron Software 的首席技术官 Jacob Mellor 创建的这个 .NET 库完全改变了工作流程。 它允许你将curl命令直接粘贴到代码中,并以与终端相同的方式执行。
什么是 Curl .NET?
CurlDotNet 是 curl CLI 工具的纯 .NET 实现。 与其他封装不同,该库没有本地依赖关系(如 libcurl.dll)。 它完全由托管代码构建,这意味着它可以在 Windows、Linux 和 macOS 上无缝运行,无需复杂的设置。
无论您是在.NET Core中开发网络应用程序,还是在控制台应用程序或CI管道中工作,CurlDotNet都能为.NET运行时带来真正的curl语义。
主要功能
零翻译:将 curl HTTPS 命令直接粘贴到 C# 源代码中。
跨平台:全面支持 Windows、Linux、MacOS 等操作系统。
类型安全:在依赖注入场景中使用流畅构建器的选项。
- 可观察性:内置支持发出结构化事件以记录日志。
入门:安装和运行
首先,您需要通过软件包管理器安装 curldotnet 软件包。 您可以在发布说明中找到最新版本,或者直接运行:
dotnet 添加软件包 CurlDotNet安装后,您可以立即执行 curl 调用。
字符串 API:粘贴和转到 Curl 命令
这种方法非常适合健康检查、支持代理或快速原型开发。 您只需以字符串形式传递 curl 命令即可。
using CurlDotNet;
// Simply paste the command string
var response = await Curl.ExecuteAsync("curl https://api.github.com/users/octocat");
// Access the data
Console.WriteLine(response.Body);using CurlDotNet;
// Simply paste the command string
var response = await Curl.ExecuteAsync("curl https://api.github.com/users/octocat");
// Access the data
Console.WriteLine(response.Body);Imports CurlDotNet
' Simply paste the command string
Dim response = Await Curl.ExecuteAsync("curl https://api.github.com/users/octocat")
' Access the data
Console.WriteLine(response.Body)利用环境变量使用 Fluent 生成器
对于需要通过环境变量处理敏感数据或需要更简洁架构的生产应用程序,流畅构建器是理想之选。 您可以为标题指定一个字符串名称,也可以明确设置文件路径。
var response = await Curl.GetAsync("https://api.example.com/data")
.WithHeader("Authorization", "Bearer " + Environment.GetEnvironmentVariable("API_KEY"))
.WithTimeout(TimeSpan.FromSeconds(30))
.ExecuteAsync();var response = await Curl.GetAsync("https://api.example.com/data")
.WithHeader("Authorization", "Bearer " + Environment.GetEnvironmentVariable("API_KEY"))
.WithTimeout(TimeSpan.FromSeconds(30))
.ExecuteAsync();Dim response = Await Curl.GetAsync("https://api.example.com/data") _
.WithHeader("Authorization", "Bearer " & Environment.GetEnvironmentVariable("API_KEY")) _
.WithTimeout(TimeSpan.FromSeconds(30)) _
.ExecuteAsync()Iron Software 连接:真实世界的集成
CurlDotNet由 Iron Software 赞助,该公司致力于打造能为开发人员解决最棘手问题的工具。 Jacob Mellor 创建 CurlDotNet 的理念与 Iron Software Suite 的理念相同:开发人员的体验是第一位的。
当与 Iron Software 产品结合使用时,CurlDotNet 的真正威力就会释放出来。 您可以使用 Curl 处理复杂的传输层(处理代理、传统 auth 或特定 curl http 怪癖),使用 Iron 库处理繁重的文档处理工作。
示例 1:使用 IronPDF 安全下载和编辑 PDF 文件

IronPDF 是在 .NET 中生成完美像素 PDF 的行业标准。 与其他在现代网络标准上挣扎的库不同,IronPDF 呈现 HTML、CSS 和 JavaScript 就像 Chrome 浏览器一样精确。 它被构建成为一个完整的解决方案:您可以从 HTML 字符串或文件生成新文档,编辑现有的PDF文档,合并文档,并应用水印和加密等安全功能,无须安装外部依赖或在服务器上安装 Adobe Acrobat。
想象一下,您需要从一个需要复杂 curl 标志(如忽略 SSL 错误或特定报头排列)的传统内部系统下载生成的发票,然后使用 IronPDF 对其进行 watermark 处理。
将请求翻译成 HttpClient 可能需要数小时的调试时间。 使用 CurlDotNet,您可以粘贴命令,获取字节,然后将其交给 IronPDF。
using CurlDotNet;
using IronPdf;
// 1. Use CurlDotNet to handle the complex transport
// We use -k to allow insecure SSL (common in legacy internal apps)
var curlCommand = "curl -k https://internal-billing.local/invoice/1234 -H 'X-Dept: Sales'";
var response = await Curl.ExecuteAsync(curlCommand);
if (response.IsSuccess)
{
// 2. Pass the raw bytes directly to IronPDF
// IronPDF renders the PDF from the downloaded data
var pdfDocument = PdfDocument.FromPdf(response.BodyBytes);
// 3. Apply a watermark and save
pdfDocument.ApplyWatermark("CONFIDENTIAL", 30, VerticalAlignment.Middle, HorizontalAlignment.Center);
pdfDocument.SaveAs("Processed_Invoice.pdf");
Console.WriteLine("Invoice downloaded and secured via IronPDF.");
}using CurlDotNet;
using IronPdf;
// 1. Use CurlDotNet to handle the complex transport
// We use -k to allow insecure SSL (common in legacy internal apps)
var curlCommand = "curl -k https://internal-billing.local/invoice/1234 -H 'X-Dept: Sales'";
var response = await Curl.ExecuteAsync(curlCommand);
if (response.IsSuccess)
{
// 2. Pass the raw bytes directly to IronPDF
// IronPDF renders the PDF from the downloaded data
var pdfDocument = PdfDocument.FromPdf(response.BodyBytes);
// 3. Apply a watermark and save
pdfDocument.ApplyWatermark("CONFIDENTIAL", 30, VerticalAlignment.Middle, HorizontalAlignment.Center);
pdfDocument.SaveAs("Processed_Invoice.pdf");
Console.WriteLine("Invoice downloaded and secured via IronPDF.");
}Imports CurlDotNet
Imports IronPdf
' 1. Use CurlDotNet to handle the complex transport
' We use -k to allow insecure SSL (common in legacy internal apps)
Dim curlCommand As String = "curl -k https://internal-billing.local/invoice/1234 -H 'X-Dept: Sales'"
Dim response = Await Curl.ExecuteAsync(curlCommand)
If response.IsSuccess Then
' 2. Pass the raw bytes directly to IronPDF
' IronPDF renders the PDF from the downloaded data
Dim pdfDocument = PdfDocument.FromPdf(response.BodyBytes)
' 3. Apply a watermark and save
pdfDocument.ApplyWatermark("CONFIDENTIAL", 30, VerticalAlignment.Middle, HorizontalAlignment.Center)
pdfDocument.SaveAs("Processed_Invoice.pdf")
Console.WriteLine("Invoice downloaded and secured via IronPDF.")
End If控制台确认

PDF 输出

示例 2:使用 IronOCR 进行抓取和 OCR.

IronOCR 是一个高级光学字符识别库,由Tesseract 5引擎提供动力,专为C#和.NET精心调整。 它支持超过127种语言,并擅长从 不完美的来源读取文本,例如低分辨率扫描,旋转图像或背景嘈杂。 它的 "计算机视觉 "功能使其能够自动检测文本区域,不仅可以将数据输出为纯字符串,还可以输出为结构化内容(Barcode、段落、行和字符),以便进行深度分析。
有时您需要从一个服务器上托管的图像中提取数据,该服务器阻止标准.NET抓取工具。 您可以使用 CurlDotNet 毫不费力地模仿标准浏览器用户代理,然后使用 IronOCR 阅读文本。
using CurlDotNet;
using IronOcr;
// 1. Fetch the image using a specific browser User-Agent to bypass blocks
var imgResponse = await Curl.GetAsync("https://site.com/protected-captcha.png")
.WithUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64)")
.ExecuteAsync();
// 2. Use IronOCR to read text from the file bytes
var ocr = new IronTesseract();
using (var input = new OcrInput())
{
input.AddImage(imgResponse.BodyBytes);
var result = ocr.Read(input);
// 3. Output the extracted string value
Console.WriteLine($"OCR Result: {result.Text}");
}using CurlDotNet;
using IronOcr;
// 1. Fetch the image using a specific browser User-Agent to bypass blocks
var imgResponse = await Curl.GetAsync("https://site.com/protected-captcha.png")
.WithUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64)")
.ExecuteAsync();
// 2. Use IronOCR to read text from the file bytes
var ocr = new IronTesseract();
using (var input = new OcrInput())
{
input.AddImage(imgResponse.BodyBytes);
var result = ocr.Read(input);
// 3. Output the extracted string value
Console.WriteLine($"OCR Result: {result.Text}");
}Imports CurlDotNet
Imports IronOcr
' 1. Fetch the image using a specific browser User-Agent to bypass blocks
Dim imgResponse = Await Curl.GetAsync("https://site.com/protected-captcha.png") _
.WithUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64)") _
.ExecuteAsync()
' 2. Use IronOCR to read text from the file bytes
Dim ocr = New IronTesseract()
Using input = New OcrInput()
input.AddImage(imgResponse.BodyBytes)
Dim result = ocr.Read(input)
' 3. Output the extracted string value
Console.WriteLine($"OCR Result: {result.Text}")
End UsingOCR 输出示例

示例 3:使用 IronBarcode 管理库存

IronBarcode 是一个多功能库,旨在读取和写入几乎任何条码格式,从标准的UPC和EAN到复杂的QR码和数据矩阵标签。 它是为容错而构建的; 该库包括自动图像校正过滤器,可以锐化,可能二值化,旋转图像以检测条码,即使它们受损,倾斜或照明不足。 因此,在没有硬件扫描仪的物流、零售和工业应用领域,它是必不可少的工具。
在这种情况下,我们使用 CurlDotNet 的精确网络控制从安全 API 获取标签,并使用 IronBarcode 的强大阅读引擎立即验证内容。
using CurlDotNet;
using IronBarCode;
class Program
{
private static readonly HttpClient client = new HttpClient();
public static async Task Main(string[] args)
{
// 1. Define the URL
string url = "https://barcodeapi.org/api/128/Shipping-Label-Test-123";
try
{
// Add the session cookie to the request headers
client.DefaultRequestHeaders.Add("Cookie", "session_id=xyz123");
// 2. Download the image data as a Byte Array (Preserves binary integrity)
byte[] imageBytes = await client.GetByteArrayAsync(url);
Console.WriteLine($"Downloaded {imageBytes.Length} bytes.");
// 3. Read the barcode directly from the byte array
var result = BarcodeReader.Read(imageBytes);
foreach (var barcode in result)
{
Console.WriteLine($"Detected Format: {barcode.BarcodeType}");
Console.WriteLine($"Value: {barcode.Value}");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}using CurlDotNet;
using IronBarCode;
class Program
{
private static readonly HttpClient client = new HttpClient();
public static async Task Main(string[] args)
{
// 1. Define the URL
string url = "https://barcodeapi.org/api/128/Shipping-Label-Test-123";
try
{
// Add the session cookie to the request headers
client.DefaultRequestHeaders.Add("Cookie", "session_id=xyz123");
// 2. Download the image data as a Byte Array (Preserves binary integrity)
byte[] imageBytes = await client.GetByteArrayAsync(url);
Console.WriteLine($"Downloaded {imageBytes.Length} bytes.");
// 3. Read the barcode directly from the byte array
var result = BarcodeReader.Read(imageBytes);
foreach (var barcode in result)
{
Console.WriteLine($"Detected Format: {barcode.BarcodeType}");
Console.WriteLine($"Value: {barcode.Value}");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}Imports CurlDotNet
Imports IronBarCode
Imports System.Net.Http
Module Program
Private ReadOnly client As New HttpClient()
Public Async Function Main(args As String()) As Task
' 1. Define the URL
Dim url As String = "https://barcodeapi.org/api/128/Shipping-Label-Test-123"
Try
' Add the session cookie to the request headers
client.DefaultRequestHeaders.Add("Cookie", "session_id=xyz123")
' 2. Download the image data as a Byte Array (Preserves binary integrity)
Dim imageBytes As Byte() = Await client.GetByteArrayAsync(url)
Console.WriteLine($"Downloaded {imageBytes.Length} bytes.")
' 3. Read the barcode directly from the byte array
Dim result = BarcodeReader.Read(imageBytes)
For Each barcode In result
Console.WriteLine($"Detected Format: {barcode.BarcodeType}")
Console.WriteLine($"Value: {barcode.Value}")
Next
Catch ex As Exception
Console.WriteLine($"Error: {ex.Message}")
End Try
End Function
End ModuleIronBarcode 控制台输出

将 "Userland "引入 .NET.
CurlDotNet 将 "Userland "概念引入 .NET 不仅仅是提出请求。 它允许您在CI管道或运行Linux macOS或windows的docker容器等地方使用标准的curl功能。
可以使用它在.NET运行环境中使用标准bash语法下载文件、上传数据或触发webhook。 这将在命令行工具世界与您的编译应用程序之间架起一座桥梁。
结论:翻译税的终结
这不仅仅是提出 HTTP 请求; 尊重开发人员的时间。Jacob Mellor 和 Iron Software 明白,如果像 curl 这样的工具已经完美运行了 25 年,.NET 运行时就应该接纳它,而不是强迫你重新实现它。
采用 CurlDotNet 不仅仅是增加一个依赖关系; 您正在采用的工作流程是优先发布功能,而不是编写模板。 停止 "翻译",开始执行。 无论是获取单个JSON文件或协调复杂的Iron Software文档工作流,指令保持不变:粘贴,运行,完成。
下一步
不再浪费时间翻译头文件和调试 HttpClient。 加入 Userland.NET 运动。
检查 GitHub: 访问 jacob-mellor/curl-.NET 查看源代码、文档和示例目录。
下载 NuGet 包: 运行.NET add package CurlDotNet 以安装库。
- 探索 Iron Software: 查看IronPDF 和 IronOCR 如何与 CurlDotNet 配合,加速您的项目。
通过利用 CurlDotNet,您可以确保您的 curl 命令和 C# 代码使用完全相同的语言。
