跳過到頁腳內容
.NET幫助

銜接 CLI 簡化與 .NET : 使用 Curl DotNet 與 IronPDF for .NET

對於在快速命令列工具腳本與強大的 .NET 程式碼之間徘徊的開發人員而言,摩擦往往在於如何在 C# 中將有效的 cURL 指令翻譯成正確的 HTTP 請求。 Jacob Mellor 藉由 CurlDotNet 填補了這個缺口,CurlDotNet 是一個為了將 cURL 的熟悉感帶到 .NET 生態系統而建立的函式庫。

透過將此工具與 Iron Software 產品 (例如 IronPDFIronXL) 相結合,您可以建立功能強大的管道,透過複雜的 API 呼叫取得資料,並立即產生專業報告。 在這篇文章中,我們將看一些例子,在這些例子中,這些工具可以互相配合,讓您的專案更上一層樓。

什麼是 CurlDotNet?

CurlDotNet 是業界標準 curl 工具的純 C# .NET 實作。 與依賴於本機相依性或 libcurl 的 wrapper 不同,此程式庫提供 100% 受管理的解決方案,並完全支援 Windows、Linux、macOS 等作業系統。 它能確保與標準用戶端相同的行為,讓您只需將 API 文件中的 bash 複製指令直接貼到程式碼中即可。

快速入門與安裝

若要開始,只需在專案目錄中執行下列指令即可:

dotnet 新增套件 curldotnet

這會安裝 CurlDotNet 套件,讓您可以存取即時可用的秘訣來處理網頁請求,而無需 HttpClient 設定的開銷。

使用 Curl-Dot-Net Curl 指令。

該函式庫擅長解析字串值指令。 如果您有來自 GitHub API 頁面或內部文件的有效 curl https 字串,可以直接執行。

using CurlDotNet;

// Simply copy-paste your shell command
var command = "curl -X GET https://api.github.com/users/jacob-mellor -H 'User-Agent: curl-dot-net'";
var result = await Curl.ExecuteAsync(command);
Console.WriteLine(result.Body);
using CurlDotNet;

// Simply copy-paste your shell command
var command = "curl -X GET https://api.github.com/users/jacob-mellor -H 'User-Agent: curl-dot-net'";
var result = await Curl.ExecuteAsync(command);
Console.WriteLine(result.Body);
Imports CurlDotNet

' Simply copy-paste your shell command
Dim command As String = "curl -X GET https://api.github.com/users/jacob-mellor -H 'User-Agent: curl-dot-net'"
Dim result = Await Curl.ExecuteAsync(command)
Console.WriteLine(result.Body)
$vbLabelText   $csharpLabel

.NET 程式碼 Curl DotNet 輸出。

!a href="/static-assets/pdf/blog/curl-dotnet-guide/curl-dotnet-guide-1.webp"> 我們第一個 Curl DotNet 指令的輸出。

對於那些偏好結構化方法的人,fluent builder 提供了簡潔的 API 來設定標頭、curl 選項和存取標記。

var response = await Curl.GetAsync("https://api.github.com/users/ironsoftware")
    .WithHeader("Authorization", "Bearer YOUR_TOKEN")
    .WithHeader("X-API-Key", "12345")
    .ExecuteAsync();
var response = await Curl.GetAsync("https://api.github.com/users/ironsoftware")
    .WithHeader("Authorization", "Bearer YOUR_TOKEN")
    .WithHeader("X-API-Key", "12345")
    .ExecuteAsync();
Dim response = Await Curl.GetAsync("https://api.github.com/users/ironsoftware") _
    .WithHeader("Authorization", "Bearer YOUR_TOKEN") _
    .WithHeader("X-API-Key", "12345") _
    .ExecuteAsync()
$vbLabelText   $csharpLabel

此彈性處理 TLS 握手機制、速率限制和內部錯誤處理,模仿 curl 可執行檔的預設行為。

在 .NET Framework 中與 Iron Software 集成

當您將 CurlDotNet 的輸出導入 Iron Software 工具時,真正的威力便會釋放出來。 由於 CurlDotNet 處理傳輸層(取得 JSON、檔案或 HTML),Iron Software 產品可以專注於處理這些內容。

情境:從 API 資料產生 PDF 報告

假設您需要從安全的 URL 下載使用者資料並產生 PDF 報告。 API 需要特定的 bash 簽名,使用 HttpClient 較難複製,但使用 curl 指令卻很容易。

步驟 1:使用 Curl-Dot-Net 抓取資料

// Define the curl command string with all necessary headers (here we use an example test website)
string curlCmd = "curl https://www.w3.org/TR/html4/ -H 'X-API-Key: secure_key'";

// Execute the request
var result = await Curl.ExecuteAsync(curlCmd);

// Extract the content (assumed to be HTML for this scenario)
string htmlContent = result.Body;
// Define the curl command string with all necessary headers (here we use an example test website)
string curlCmd = "curl https://www.w3.org/TR/html4/ -H 'X-API-Key: secure_key'";

// Execute the request
var result = await Curl.ExecuteAsync(curlCmd);

// Extract the content (assumed to be HTML for this scenario)
string htmlContent = result.Body;
Imports System.Threading.Tasks

' Define the curl command string with all necessary headers (here we use an example test website)
Dim curlCmd As String = "curl https://www.w3.org/TR/html4/ -H 'X-API-Key: secure_key'"

' Execute the request
Dim result = Await Curl.ExecuteAsync(curlCmd)

' Extract the content (assumed to be HTML for this scenario)
Dim htmlContent As String = result.Body
$vbLabelText   $csharpLabel

第 2 步:使用 IronPDF 生成 PDF.

IronPDF是一個功能強大的函式庫,可將HTML、CSS、JavaScript圖片渲染成高逼真度的 PDF 文件。 它提供對現代網頁標準的完整支援,並包含新增頁頭、頁尾及設定特定呈現選項等功能。

using IronPdf;

// Instantiate the renderer
var renderer = new ChromePdfRenderer();

// Convert the fetched HTML data to PDF
var pdf = renderer.RenderHtmlAsPdf(htmlContent);

// Save the file to the output path
pdf.SaveAs("output.pdf");
using IronPdf;

// Instantiate the renderer
var renderer = new ChromePdfRenderer();

// Convert the fetched HTML data to PDF
var pdf = renderer.RenderHtmlAsPdf(htmlContent);

// Save the file to the output path
pdf.SaveAs("output.pdf");
Imports IronPdf

' Instantiate the renderer
Dim renderer As New ChromePdfRenderer()

' Convert the fetched HTML data to PDF
Dim pdf = renderer.RenderHtmlAsPdf(htmlContent)

' Save the file to the output path
pdf.SaveAs("output.pdf")
$vbLabelText   $csharpLabel

輸出

 使用 CurlDotNet 和 IronPDF 將網站轉換為 PDF 的測試

情境:將 JSON 匯出至 Excel

如果您的應用程式會消耗 JSON feed,您可以使用 CurlDotNet 的測試功能取得,並使用 IronXL 匯出。

步驟 1:使用 Curl-Dot-Net 抓取 JSON 資料

我們使用流暢的建構器來執行乾淨的 .NET 程式碼,以取得 JSON feed:

string testUrl = "https://jsonplaceholder.typicode.com/users";

Console.WriteLine($"Executing HTTP request to fetch JSON from: {testUrl}");
// Replace the CurlDotNet fluent builder usage with the correct async method
var response = await Curl.GetAsync(testUrl); // Use Curl.GetAsync() for async HTTP GET

string jsonBody = response.Body;
string testUrl = "https://jsonplaceholder.typicode.com/users";

Console.WriteLine($"Executing HTTP request to fetch JSON from: {testUrl}");
// Replace the CurlDotNet fluent builder usage with the correct async method
var response = await Curl.GetAsync(testUrl); // Use Curl.GetAsync() for async HTTP GET

string jsonBody = response.Body;
Imports System

Dim testUrl As String = "https://jsonplaceholder.typicode.com/users"

Console.WriteLine($"Executing HTTP request to fetch JSON from: {testUrl}")
' Replace the CurlDotNet fluent builder usage with the correct async method
Dim response = Await Curl.GetAsync(testUrl) ' Use Curl.GetAsync() for async HTTP GET

Dim jsonBody As String = response.Body
$vbLabelText   $csharpLabel

步驟 2:使用 IronXL.Excel 載入並匯出至 Excel。

IronXL是一個全面的 .NET 函式庫,設計用來處理 讀取寫入和操作 Excel 檔案格式 (.xlsx、.xls、.csv) 的所有方面。 最重要的是,它不需要在伺服器或用戶端機器上安裝 Microsoft Office,因此非常適合跨平台的 Linux 和 CI CD 環境。 主要功能包括完全支援建立圖表、套用公式及儲存格造型。

現在原始 JSON 資料已經成為字串,可以使用 IronXL 來解析並建立試算表。

var workbook = WorkBook.Create(ExcelFileFormat.XLSX);
 var sheet = workbook.CreateWorkSheet("User Data");

 // 1. Deserialize the JSON string to a list of UserRecord objects
 Console.WriteLine("Deserializing JSON data...");
 var salesRecords = JsonConvert.DeserializeObject<List<UserRecord>>(jsonBody);

 // 2. Insert the data into the sheet using IronXL's SetCellValue method
 Console.WriteLine("Inserting data into Excel using IronXL...");

 // Write headers
 sheet.SetCellValue(0, 0, "id");
 sheet.SetCellValue(0, 1, "name");
 sheet.SetCellValue(0, 2, "username");
 sheet.SetCellValue(0, 3, "email");

 // Write data rows
 for (int i = 0; i < salesRecords.Count; i++)
 {
     var record = salesRecords[i];
     sheet.SetCellValue(i + 1, 0, record.id);
     sheet.SetCellValue(i + 1, 1, record.name);
     sheet.SetCellValue(i + 1, 2, record.username);
     sheet.SetCellValue(i + 1, 3, record.email);
 }

 // Save the Excel file
 string filePath = "UserReport.xlsx";
 workbook.SaveAs(filePath);

 Console.WriteLine($"\n Success! Excel report saved to: {Path.GetFullPath(filePath)}");
var workbook = WorkBook.Create(ExcelFileFormat.XLSX);
 var sheet = workbook.CreateWorkSheet("User Data");

 // 1. Deserialize the JSON string to a list of UserRecord objects
 Console.WriteLine("Deserializing JSON data...");
 var salesRecords = JsonConvert.DeserializeObject<List<UserRecord>>(jsonBody);

 // 2. Insert the data into the sheet using IronXL's SetCellValue method
 Console.WriteLine("Inserting data into Excel using IronXL...");

 // Write headers
 sheet.SetCellValue(0, 0, "id");
 sheet.SetCellValue(0, 1, "name");
 sheet.SetCellValue(0, 2, "username");
 sheet.SetCellValue(0, 3, "email");

 // Write data rows
 for (int i = 0; i < salesRecords.Count; i++)
 {
     var record = salesRecords[i];
     sheet.SetCellValue(i + 1, 0, record.id);
     sheet.SetCellValue(i + 1, 1, record.name);
     sheet.SetCellValue(i + 1, 2, record.username);
     sheet.SetCellValue(i + 1, 3, record.email);
 }

 // Save the Excel file
 string filePath = "UserReport.xlsx";
 workbook.SaveAs(filePath);

 Console.WriteLine($"\n Success! Excel report saved to: {Path.GetFullPath(filePath)}");
Imports IronXL
Imports Newtonsoft.Json
Imports System.IO

Dim workbook = WorkBook.Create(ExcelFileFormat.XLSX)
Dim sheet = workbook.CreateWorkSheet("User Data")

' 1. Deserialize the JSON string to a list of UserRecord objects
Console.WriteLine("Deserializing JSON data...")
Dim salesRecords = JsonConvert.DeserializeObject(Of List(Of UserRecord))(jsonBody)

' 2. Insert the data into the sheet using IronXL's SetCellValue method
Console.WriteLine("Inserting data into Excel using IronXL...")

' Write headers
sheet.SetCellValue(0, 0, "id")
sheet.SetCellValue(0, 1, "name")
sheet.SetCellValue(0, 2, "username")
sheet.SetCellValue(0, 3, "email")

' Write data rows
For i As Integer = 0 To salesRecords.Count - 1
    Dim record = salesRecords(i)
    sheet.SetCellValue(i + 1, 0, record.id)
    sheet.SetCellValue(i + 1, 1, record.name)
    sheet.SetCellValue(i + 1, 2, record.username)
    sheet.SetCellValue(i + 1, 3, record.email)
Next

' Save the Excel file
Dim filePath As String = "UserReport.xlsx"
workbook.SaveAs(filePath)

Console.WriteLine(vbCrLf & " Success! Excel report saved to: " & Path.GetFullPath(filePath))
$vbLabelText   $csharpLabel

輸出 Excel 文件

!a href="/static-assets/pdf/blog/curl-dotnet-guide/curl-dotnet-guide-3.webp"> 使用 CurlDotNet 和 IronExcel 建立的 Excel 檔案。

為何選擇此組合?

1.跨平台一致性: CurlDotNetIronSoftware產品皆支援 Windows、Linux 和 macOS。 這對於在 Microsoft Azure 或 AWS Lambda 等運行環境上執行的 CI CD 管道至關重要。

2.程式碼產生:開發人員經常會收到 bash 或 shell 格式的程式碼產生片段。 curl-dot-net 可讓您直接使用這些程式碼片段,而 Iron Software 則負責處理繁重的文件操作。

3.無本機相依性:由於 CurlDotNet 是純 C# 實現,因此可以避免在不同作業系統版本上連結外部 C++ 函式庫或 libcurl 二進位檔案時常見的各種問題。

結論

Jacob Mellor 為 DotNet 社群提供了重要的工具。 透過允許開發人員在 .NET Framework 和 Core 應用程式中使用熟悉的 curl 選項,CurlDotNet 簡化了 http 請求流程。 與 Iron Software 搭配使用時,您可以建立無縫的工作流程:利用 curl 的精確性取得資料,並利用 IronPDF 或 IronXL 的強大功能處理資料。

如果您遇到問題,請務必在 GitHub 頁面上回報錯誤,以協助改善對每位使用者的支援。

常見問題解答

什麼是 CurlDotNet?

CurlDotNet 是 Jacob Mellor 創建的函式庫,將 cURL 的功能帶入 .NET 生態系統,讓開發人員可以輕鬆地將 cURL 指令翻譯成 .NET 程式碼。

CurlDotNet 如何幫助開發人員?

CurlDotNet 透過簡化在 C# 中將 cURL 指令列作業翻譯為 HTTP 請求的流程來幫助開發人員,讓他們更容易將指令列工具腳本整合到強大的 .NET 應用程式中。

CurlDotNet 能解決什麼問題?

CurlDotNet 可解決開發人員在嘗試將運作中的 cURL 指令轉換為 C# 中正確的 HTTP 請求時所遇到的摩擦問題。它為那些習慣了 cURL 簡單性的人提供了一種熟悉的方法。

CurlDotNet 可以與 IronPDF 搭配使用嗎?

是的,CurlDotNet 可與 IronPDF 一同使用,以提高 HTTP 請求的簡易性,作為 .NET 應用程式中 PDF 生成工作流程的一部分。

CurlDotNet 適合初學者嗎?

是的,CurlDotNet 適合初學者使用,因為它提供了熟悉的命令列式介面,可以減輕初學者對 .NET 和 HTTP 請求的學習曲線。

使用 CurlDotNet 與 IronPDF 有什麼好處?

將 CurlDotNet 與 IronPDF 搭配使用,可讓開發人員在生成 PDF 的同時簡化 HTTP 請求,提高效率並發揮兩種工具的優勢。

我可以在哪裡瞭解更多關於 CurlDotNet 的資訊?

您可以造訪 Jacob Mellor 在 Medium 上發表的文章,瞭解更多關於 CurlDotNet 的資訊,其中詳細介紹了該函式庫如何縮短 cURL 指令與 .NET 程式碼之間的距離。

Jacob Mellor, Team Iron 首席技術官
首席技術官

Jacob Mellor是Iron Software的首席技術官,也是開創C# PDF技術的前瞻性工程師。作為Iron Software核心代碼庫的原始開發者,他自公司成立以來就塑造了公司的產品架構,並與CEO Cameron Rimington將公司轉型為服務NASA、Tesla以及全球政府機構的50多人公司。

Jacob擁有曼徹斯特大學土木工程一級榮譽學士學位(1998年–2001年)。他於1999年在倫敦開立首家軟體公司,並於2005年建立了他的第一個.NET組件,專注於解決Microsoft生態系統中的複雜問題。

他的旗艦作品IronPDF和Iron Suite .NET程式庫全球已獲得超過3000萬次NuGet安裝,他的基礎代碼不斷在全球各地驅動開發者工具。擁有25年以上的商業經驗和41年的編碼專業知識,Jacob仍然專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

鋼鐵支援團隊

我們每週 5 天,每天 24 小時在線上。
聊天
電子郵件
打電話給我