IRON SUITEの使用

Curl DotNet:.NETランタイムにCurlのスーパーパワーをもたらす

新しいAPIのドキュメントを読んでいて、プロバイダからエンドポイントをテストするためのcurlコマンドを渡される。 あなたはコマンドラインツールの構文を見つめ、ため息をつき、それをC#の新しいHttpClientインスタンスに翻訳する退屈なプロセスを開始します。

ヘッダーを手作業でマッピングし、本文の文字列値が正しくエンコードされていることを確認し、ユーザーエージェントを処理し、サイレントデフォルトを見逃していないことを祈る必要があります。 この手作業によるbashのコピーと翻訳プロセスは、エラーが発生しやすいものです。 ヘッダーが1つでも欠けると、HTTPリクエストは失敗します。

CurlDotNet を入力してください。 IronソフトウェアのCTOであるJacob Mellorによって作成されたこ for .NETライブラリは、ワークフローを完全に変えます。 curlコマンドをコードに直接貼り付け、ターミナルから期待するのと同じ動作で実行することができます。

Curl .NETとは何か?

CurlDotNet は、curl CLIツールの純粋な.NET実装です。 他のラッパーとは異なり、このライブラリにはネイティブの依存関係がありません(libcurl.dll のような)。 完全にマネージドコードで構築されているため、複雑な設定なしにWindows、Linux、macOS上でシームレスに動作します。

NET CoreのWebアプリ、コンソールアプリケーション、またはCIパイプラインのいずれで作業していても、CurlDotNetは.NETランタイムに真のcurlセマンティクスをもたらします。

主要機能

  • ゼロ翻訳: C#ソースにcurl HTTPSコマンドを直接貼り付けます。

  • クロスプラットフォーム: Windows、Linux、MacOSなどをフルサポート。

  • 型安全性: 依存性注入シナリオのために流暢なビルダーを使用するオプション。

  • 観測可能性: ロギング用に構造化されたイベントを発行するための組み込みサポート。

はじめに:インストールと実行

始めるには、パッケージマネージャ経由でcurldotnetパッケージをインストールする必要があります。 最新バージョンはリリースノートでご覧になれます:

dotnet add パッケージ 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

環境変数を使用したFluent Builderの使用

環境変数を使って機密データを扱う必要がある場合や、よりクリーンなアーキテクチャを必要とする本番アプリケーションには、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();
Dim response = Await Curl.GetAsync("https://api.example.com/data") _
    .WithHeader("Authorization", "Bearer " & Environment.GetEnvironmentVariable("API_KEY")) _
    .WithTimeout(TimeSpan.FromSeconds(30)) _
    .ExecuteAsync()
$vbLabelText   $csharpLabel

ソフトウェア・コネクション:実世界での統合

CurlDotNetは、開発者にとって最も困難な問題を解決するツールの構築に専念しているIron Softwareによって後援されています。 Jacob Mellorは、CurlDotNetを、Iron Softwareスイートの原動力である"開発者の体験を第一に"という同じ哲学に基づいて作成しました。

CurlDotNetの真のパワーは、Iron Software製品と組み合わせることで発揮されます。 複雑なトランスポートレイヤー(プロキシ、レガシー認証、または特定のcurl httpの癖を処理する)にはCurlを使用し、ドキュメント処理の重労働にはIronライブラリを使用することができます。

例1: IronPDFによる安全なPDFのダウンロードと編集

IronPDF

IronPDFは、.NETでピクセルパーフェクトなPDFを生成するための業界標準です。 他のライブラリが現代のウェブ標準で苦戦する中、IronPDFはHTMLCSS、および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
$vbLabelText   $csharpLabel

コンソールの確認

PDFが保存されたことを確認するためにコンソールに書き込みが行われます

PDF出力

例: 出力されたPDFファイル

例2: IronOCRによるスクレイピングとOCR

IronOCR

IronOCRは、特にC#と.NET向けに調整されたTesseract 5エンジンによって駆動される高度な光学文字認識ライブラリです。 127以上の言語をサポートし、解像度が低いスキャン、回転された画像、あるいは雑音の多い背景といった不完全なソースからテキストを読み取るのに優れています。 コンピュータ・ビジョン"機能により、テキスト領域を自動的に検出し、データを単なる文字列としてだけでなく、構造化されたコンテンツ(BarCode、段落、行、文字)として出力し、深く分析することができます。

時々、標準 for .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出力例

CurlDotNetを使用したIronOCRの例出力

例3: IronBarcodeで在庫を管理する

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}");
        }
    }
}
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 コンソール出力

CurlDotNetを使用したIronBarcodeの例出力

.NETに"ユーザーランド"をもたらす

CurlDotNetは、.NETに "ユーザーランド "のコンセプトをもたらすことで、単にリクエストするだけではありません。 これにより、Linux macOSやwindowsを実行するCIパイプラインやdockerコンテナのような場所で、標準的なcurlの機能を使用することができます。

標準のbash構文を使用して.NETランコンテキスト内でファイルをダウンロードしたり、データをアップロードしたり、Webhookをトリガーしたりすることができます。 これは、コマンドラインツールの世界とコンパイルされたアプリケーションとのギャップを埋めるものです。

結論:翻訳税の終焉

HTTPリクエストを行うだけではありません; それは、開発者の時間を尊重することです。Jacob Mellorとソフトウェアは、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#コードが全く同じ言語を話すことを保証します。