Curl DotNet:為 .NET Runtime 帶來 Curl 超強功能
對於每個.NET開發人員來說,這種情況都非常熟悉:您正在閱讀新 API 的文檔,提供者為您提供了一個 curl 命令來測試端點。 你盯著命令列工具的語法,嘆了口氣,然後開始將其轉換為 C# 中的新 HttpClient 實例的繁瑣過程。
你必須手動映射標頭,確保正文的字串值編碼正確,處理用戶代理,並希望你沒有遺漏靜默預設值。 這種手動複製和翻譯 bash 腳本的過程容易出錯。 缺少一個標頭,您的 HTTP 請求就會失敗。
進入CurlDotNet 。 該.NET庫由Iron Software的首席技術官 Jacob Mellor 創建,它徹底改變了工作流程。 它允許您將 curl 命令直接貼上到程式碼中,並以與終端預期相同的行為執行它們。
什麼是 Curl DotNet?
CurlDotNet是 curl CLI 工具的純.NET實作。 與其他封裝庫不同,該程式庫沒有原生依賴項(如 libcurl.dll)。 它完全採用託管程式碼構建,這意味著它可以在 Windows、Linux 和 macOS 上無縫運行,無需複雜的設定。
無論您是在開發 .NET Core 中的 Web 應用程式、控制台應用程式還是 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);使用 Fluent Builder 和環境變量
對於需要透過環境變數處理敏感資料或需要更清晰架構的生產應用程式而言,流暢建構器是理想之選。 您可以為標頭指定字串名稱,也可以明確設定檔案路徑。
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();Iron Software Connection:真實世界的集成
CurlDotNet由Iron Software贊助,該公司致力於建立能夠解決開發人員最棘手問題的工具。 Jacob Mellor 創建 CurlDotNet 的概念與Iron Software套件的概念相同:開發者體驗至上。
CurlDotNet 與Iron Software產品結合使用時,才能真正發揮其強大功能。 您可以使用 Curl 處理複雜的傳輸層(處理代理程式、舊式驗證或特定的 curl http 怪癖),並使用 Iron 程式庫進行繁重的文件處理。
範例 1:使用IronPDF安全地下載和編輯 PDF 文件

IronPDF是.NET中產生像素級完美 PDF 的業界標準。 與其他難以適應現代 Web 標準的函式庫不同, IronPDF可以像 Chrome 瀏覽器一樣渲染 HTML 、 CSS和JavaScript 。 它旨在成為一個完整的解決方案:您可以從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.");
}控制台確認

PDF 輸出

範例 2:使用IronOCR進行刮擦和 OCR 處理

IronOCR是一個由Tesseract 5 引擎驅動的高級光學字元辨識庫,專門針對 C# 和.NET進行了微調。 它支援超過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}");
}OCR 範例輸出

範例 3:使用IronBarcode管理庫存

IronBarcode是一個功能全面的函式庫,旨在讀取和寫入幾乎任何條碼格式,從標準的 UPC 和 EAN 到複雜的 QR 碼和 Data Matrix 標籤。 它具有容錯能力; 該庫包含自動影像校正濾鏡,可銳利化、可能二值化和旋轉影像,即使條碼損壞、傾斜或光線不足,也能偵測條碼。 這使其成為物流、零售和工業應用領域必不可少的工具,因為在這些領域,硬體掃描器無法使用。
在這種情況下,我們使用 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}");
}
}
}IronBarcode控制台輸出

將"用戶空間"引入.NET
CurlDotNet 將"使用者空間"概念引入.NET ,其意義遠不止於發出請求。 它允許您在諸如 CI 管道或運行 Linux、macOS 或 Windows 的 docker 容器等地方使用標準的 curl 功能。
您可以使用它在 DotNet 運行上下文中使用標準 bash 語法下載檔案、上傳資料或觸發 webhook。 這彌合了命令列工具世界和已編譯應用程式之間的差距。
結論:翻譯稅的終結
這不僅是發出HTTP請求的問題; 這關乎對開發者時間的尊重。 Jacob Mellor 和Iron Software深知,如果像 curl 這樣的工具已經完美運行了 25 年,那麼.NET運行時就應該直接採用它,而不是強迫你重新實現它。
採用 CurlDotNet,你不只是增加了一個依賴項; 你採用了一種優先交付功能而非編寫樣板程式碼的工作流程。 你停止"翻譯",開始執行。 無論您是取得單一 JSON 檔案還是編排複雜的Iron Software文件工作流程,指令都是一樣的:貼上、運行、完成。
後續步驟
別再浪費時間翻譯請求頭和調試HttpClient了。 加入用戶態.NET運動。
1.查看GitHub:造訪jacob-mellor/curl-dot-net查看原始程式碼、文件和範例目錄。
2.下載NuGet套件:執行 DotNet add package CurlDotNet 安裝庫。
3.探索Iron Software:了解IronPDF和IronOCR如何與 CurlDotNet 協同工作,加速您的專案。
透過利用 CurlDotNet,您可以確保您的 curl 命令和 C# 程式碼使用完全相同的語言。
