銜接 CLI 簡化與 .NET : 使用 Curl DotNet 與 IronPDF for .NET
對於開發者來說,在快速的命令行工具腳本與穩健的.NET程式碼之間的鴻溝,往往在於將工作中的cURL命令轉化為C#中的適當HTTP請求時的摩擦。 Jacob Mellor已通過CurlDotNet彌補了這一鴻溝,這是一個專為將cURL的熟悉度帶入.NET生態系統而建立的程式庫。
通過將此工具與Iron Software產品如IronPDF或IronXL相結合,您可以建立強大的管線,通過複雜的API調用獲取資料並立即生成專業報告。 在這篇文章中,我們將看看一些範例,這些工具如何一起工作來提升您的專案到新的高度。
什麼是CurlDotNet?
CurlDotNet是業界標準curl工具的純C# .NET實現。 不同於依賴於原生依賴或libcurl的包裝器,這個程式庫提供了一個100%托管的解決方案,完全支持Windows、Linux、macOS等。 它保證與標準客戶端相同的行為,讓您能夠簡單地直接將來自API文件的bash命令複製粘貼到程式碼中。
快速開始和安裝
要開始,請簡單地在您的專案目錄中運行以下命令:
dotnet add package curldotnet
這將安裝CurlDotNet包,讓您可以使用現成的配方來處理Web請求,而無需配置HttpClient的開銷。
使用Curl-.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)
.NET程式碼Curl .NET輸出

對於那些喜歡結構化方法的人,流暢的構建器提供了一個清晰的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()
這種靈活性能夠內部處理TLS握手機制、速率限制和錯誤處理,模仿curl執行檔的預設行為。
與.NET Framework中的Iron Software整合
當您將CurlDotNet的輸出導入到Iron Software工具時,真正的威力將被釋放。 由於CurlDotNet負責傳輸層(獲取JSON、文件或HTML),Iron Software產品則可專注於處理這些內容。
情景:從API資料生成PDF報告
想像一下,您需要從一個安全的URL下載使用者資料並生成PDF報告。 該API需要一個特定的bash簽名,這很難用HttpClient複製,但用curl命令則很容易。
步驟1:使用Curl-.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
步驟2:使用IronPDF生成PDF
IronPDF是一個強大的程式庫,專為將HTML、CSS、JavaScript和圖片渲染為高保真度PDF文件而設計。 它完全支持現代Web標準,並包含如新增標題、頁腳及設置特定渲染選項的功能。
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")
輸出

情景:將JSON導出到Excel
如果您的應用程式消耗一個JSON資料流,您可以使用CurlDotNet的測試功能檢索它,然後使用IronXL導出。
步驟1:使用Curl-.NET獲取JSON資料
我們使用流暢的構建器來撰寫乾淨的.NET程式碼以獲取JSON資料流:
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
步驟2:使用IronXL載入並導出到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))
輸出Excel文件

為什麼選擇這種組合?
-
跨平台一致性: CurlDotNet和Iron Software產品均支持Windows、Linux和macOS。 這對於運行在Microsoft Azure或AWS Lambda等執行環境中的CI CD管線來說至關重要。
-
程式碼生成: 開發者經常收到以bash或shell格式提供的程式碼生成片段。 curl-.NET允許您直接使用這些片段,而Iron Software負責處理文件操作的繁重工作。
- 無原生依賴: 由於CurlDotNet是純C#實現,您可以避免連結不同操作系統版本上的外部C++庫或libcurl二進制檔案時的常見問題。
結論
Jacob Mellor為.NET社區提供了一個重要工具。 通過允許開發者在.NET Framework和Core應用中使用熟悉的curl選項,CurlDotNet簡化了HTTP請求過程。 與Iron Software搭配使用時,您可以建立無縫的工作流程:以curl的精確度獲取資料,並以IronPDF或IronXL的強大功能處理。
若您遇到問題,請務必在GitHub頁面報告錯誤,以幫助改善對每位使用者的支援。
常見問題
什麼是CurlDotNet?
CurlDotNet是Jacob Mellor建立的一個程式庫,用於將cURL的功能引入.NET生態系統,使開發人員可以輕鬆地將cURL命令轉換為.NET程式碼。
CurlDotNet如何幫助開發人員?
CurlDotNet透過簡化將cURL命令行操作轉換為C#中的HTTP請求的過程來幫助開發人員,便於將命令行工具腳本整合到強大的.NET應用程式中。
CurlDotNet解決了什麼問題?
CurlDotNet解決了開發人員在嘗試將工作中的cURL命令轉換為C#中的適當HTTP請求時遇到的摩擦問題。它為習慣於cURL簡易性的人提供了一種熟悉的方法。
CurlDotNet可以與IronPDF一起使用嗎?
是的,CurlDotNet可以與IronPDF一起使用,以增强在.NET應用程式中生成PDF工作流時進行HTTP請求的便利性。
CurlDotNet是否適合初學者?
是的,CurlDotNet適合初學者,因為它提供了一個熟悉的命令行風格介面,使新手在學習.NET和HTTP請求時更簡單。
將CurlDotNet與IronPDF一起使用的好處是什麼?
將CurlDotNet與IronPDF一起使用可以在生成PDF時精簡HTTP請求,提高效率,並利用兩者的優勢。
我可以在哪裡了解更多關於CurlDotNet的資訊?
您可以造訪Jacob Mellor在Medium上的文章,以了解更多關於如何將這個程式庫在cURL命令和.NET程式碼之間搭建橋樑的詳細見解。




