Curl DotNet:把Curl的超能力帶入.NET運行時
對於每位 .NET 開發者來說,這種情境再熟悉不過:您正在閱讀一個新 API 的文件,提供者給了您一個 curl 命令來測試端點。 您盯著命令行工具語法,嘆氣,然後開始將其轉換成 C# 中新的 HttpClient 實例的乏味過程。
您必須手動映射標頭,確保正文的字串值正確編碼,處理用戶代理,並希望您沒有遺漏任何默認值。 這個手動 bash 複製和翻譯過程容易出錯。 少了一個標頭,您的 HTTP 請求就會失敗。
進入 CurlDotNet。 由 Iron Software 的 CTO Jacob Mellor 創建,這個 .NET 程式庫徹底改變了工作流程。 它允許您直接將 curl 命令粘貼到您的代碼中,並以您期望終端中的相同行為執行它們。
Curl .NET 是什麼?
CurlDotNet 是 curl CLI 工具的純 .NET 實現。 與其他包裝程式不同,這個程式庫沒有本地依賴項(如 libcurl.dll)。 它完全建立於管理代碼中,這意味著它可以在 Windows、Linux 和 macOS 上無縫運行,無需複雜的設置。
無論您是正在處理 Net Core 的 Web 應用程序、控制台應用程序還是 CI 管道,CurlDotNet 都可以將真正的 curl 語義帶到 .NET 執行時。
主要功能
零翻譯:將 curl HTTPS 命令直接粘貼到您的 C# 來源中。
跨平台:全面支持 Windows、Linux、Mac OS 等。
類型安全:可選使用流暢的構建器來支持依賴注入場景。
- 可觀測性:內建支援以結構化事件形式發出日誌。
入門:安裝和運行
首先,您需要通過包管理器安裝 curldotnet。 您可以在發布說明中找到最新版本,或簡單地運行:
dotnet add package 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)使用環境變量的流暢構建器
對於需要通過環境變量處理敏感數據的生產應用程序,或需要更清晰的架構,流暢的構建器是理想的選擇。 您可以指定標頭的字串名稱或明確設置文件路徑。
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 套件的理念相同:開發者體驗至上。
當與 Iron Software 產品結合時,CurlDotNet 的真正威力得以釋放。 您可以將 Curl 用於複雜的傳輸層(如處理代理、舊版身份驗證或特定的 curl http 怪癖),而將 Iron 程式庫用於文檔處理的繁重工作。
示例 1:使用 IronPDF 進行安全 PDF 下載與編輯

IronPDF 是 .NET 中生成像素完美 PDF 的行業標準。 與那些難以應對現代網頁標準的其他程式庫不同,IronPDF 渲染 HTML、CSS 和 JavaScript 與 Chrome 瀏覽器的方法完全相同。 它旨在成為一個完整的解決方案:您可以從 HTML 字串 或 文件 生成新文件,編輯現有的 PDF,合併文件,並應用如水印和加密等安全功能,無需外部依賴項或在伺服器上安裝 Adobe Acrobat。
想像一下,您需要從需要複雜 curl 標誌(如忽略 SSL 錯誤或特定標頭排列)的舊版內部系統中下載生成的發票,然後使用 IronPDF 水印。
將該請求翻譯為 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 是一個高級光學字符識別程式庫,由專為 C# 和 .NET 調整的 Tesseract 5 引擎 提供動力。 它支持超過127 種語言,擅長從不完美來源讀取文本 —— 想想低分辨率掃描、旋轉圖像或背景噪聲的情況。 其"電腦視覺"功能允許它自動檢測文本區域,並且不僅能以純字符串形式輸出數據,還能以結構化內容(條形碼、段落、行和字符)輸出,以進行深入分析。
有時候您需要從服務器上托管且阻止標準 .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 語法觸發 webhooks。 這填補了命令行工具世界和您的編譯應用程序之間的鴻溝。
結論:翻譯稅的終結
這不僅僅是發出 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# 代碼使用相同的語言。
