使用IRON SUITE

掌握.NET 10中的Async/Await C#:可擴展應用程式的基本指南

對於每位.NET開發者來說,這種情境再熟悉不過:您正在閱讀新API的文件,而提供者給您一個curl命令來測試端點。 您盯著命令行工具的語法,嘆息,然後開始翻譯它為C#中的一個新HttpClient實例的繁瑣過程。

您必須手動映射標頭,確保正文的字串值正確編碼,處理使用者代理,並希望您沒有錯過一個無聲的預設值。 這種手動bash複製和翻譯過程容易出錯。 缺少一個標頭,您的HTTP請求就會失敗。

Enter CurlDotNet. 由Iron Software的CTO Jacob Mellor建立,這個.NET程式庫徹底改變了工作流程。 它允許您直接將curl命令粘貼到您的程式碼中並以您期望的終端行為執行它們。

Curl .NET是什麼?

CurlDotNet是curl CLI工具的純.NET實現。 與其他封裝不同,這個程式庫沒有本地依賴(如libcurl.dll)。 它完全使用受管程式碼構建,這意味著它可以在Windows、Linux和macOS上無縫執行,無需複雜的設置。

無論您是在Net Core上開發網頁應用,控制台應用,還是CI管道上工作,CurlDotNet將真正的curl語義帶到.NET運行時。

主要特點

  • 零翻譯:直接將curl HTTPS命令粘貼到您的C#源程式碼中。

  • 跨平台:全力支持Windows、Linux、MacOS等。

  • 型別安全:在依賴注入場景中選擇使用流暢的建構器。

  • 可觀察性:內建支援發出結構化事件以進行日誌記錄。

快速入門:安裝和運行

首先,您需要通過包管理器安裝包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)
$vbLabelText   $csharpLabel

使用流暢建構器與環境變數

對於需要通過環境變數處理敏感資料的生產應用程式或需要更乾淨架構的情況,流暢建構器是理想選擇。 您可以為標頭指定字串名稱或顯式設置文件路徑。

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()
$vbLabelText   $csharpLabel

Iron Software連結:實際整合

CurlDotNet由Iron Software贊助,該公司致力於開發解決開發者最難問題的工具。 Jacob Mellor建立CurlDotNet的理念與Iron Software套件的理念一致:開發者體驗至上。

當與Iron Software產品結合使用時,CurlDotNet的真正力量才得以釋放。 您可以使用Curl進行複雜的傳輸層(處理代理、遺留身份驗證或特定的curl HTTP怪癖),而Iron庫則負責文件處理的繁重工作。

範例1:使用IronPDF進行安全的PDF下載和編輯

IronPDF

IronPDF是.NET行業在生成像素完美的PDF方面的標準。 與其他在現代Web標準上掙扎的程式庫不同,IronPDF 渲染HTMLCSSJavaScript 如同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
$vbLabelText   $csharpLabel

控制台確認

確認寫入至控制台確認PDF已保存

PDF輸出

範例輸出PDF文件

範例2:使用IronOCR進行抓取及OCR

IronOCR

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}");
}
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 Using
$vbLabelText   $csharpLabel

OCR範例輸出

使用IronOCR與CurlDotNet的範例輸出

範例3:使用IronBarcode進行庫存管理

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 Module
$vbLabelText   $csharpLabel

IronBarcode控制台輸出

 使用IronBarcode與CurlDotNet的範例輸出

將"Userland"帶到.NET

將CurlDotNet帶入.NET的"Userland"概念不僅僅關於發出請求。 它允許您在像CI管道或執行Linux、macOS或Windows的docker容器等地方使用標準curl功能。

您可以使用它來下載文件、上傳資料或在.NET運行環境中使用標準bash語法觸發webhooks。 這樣彌合了命令行工具世界和編譯應用程式之間的鴻溝。

結論:翻譯稅的終結

這不僅僅是發出HTTP請求; 它關乎於尊重開發者的時間。Jacob Mellor 和 Iron Software 理解到如果curl 這款工具已經完美運行了25年,那麼.NET運行時應該接受它,而不是強迫您重新實現它。

通過採用CurlDotNet,您不僅僅是在新增依賴; 您是在採用一種優先於編寫樣板程式碼的工作流程。 您停止"翻譯",開始執行。 無論是接收單個JSON文件,還是協同複雜的Iron Software文件工作流程,指令始終如一:粘貼,運行,完成。

下一步

停止浪費時間翻譯標頭和除錯HttpClient。 加入Userland.NET運動。

  1. 檢查GitHub:存取jacob-mellor/curl-.NET以查看源程式碼、文件和範例目錄。

  2. 下載NuGet軟體包:運行 .NET add package CurlDotNet 來安裝程式庫。

  3. 探索Iron Software:看看IronPDFIronOCR 如何與CurlDotNet協同工作以加速您的項目。

透過利用CurlDotNet,您確保curl命令和C#程式碼講同一種語言。