.NET 幫助

HttpListener C#(它如何為開發人員工作)

介紹

在 C# 中,用於構建基礎獨立 Web 伺服器的最有用工具之一是 HttpListener 類。 其包含在 System.Net 命名空间中,并提供一种方法用于接收和回复來自客戶端的HTTP請求。 這對於在桌面程式中管理基於網路的通信或構建輕量級的在線服務特別有幫助。

一個名為IronPDF for PDF Processing的.NET庫,用於生成、修改和提取PDF文件中的內容。 它提供了全面的功能,可以從HTML創建PDF,將現有的PDF轉換為不同格式,並使用程式設計來修改PDF。

開發人員可以結合使用 HttpListener 和 IronPDF 設計網路服務,以動態生成並提供 PDF 文件來響應 HTTP 請求。 需要根據用戶輸入或其他動態數據即時生成 PDF 的應用程序可能會發現這非常有用。

HttpListener C# 是什麼?

HttpListener 文件 是 .NET Framework 的 System.Net 命名空間中一個簡單且靈活的類別,使開發人員能夠在 C# 中設計簡單的 HTTP 伺服器。 其目的是接收客戶端的 HTTP 請求、處理它們,並以正確的資訊回覆。 由於不需要像 IIS 這樣的全功能網路伺服器,此類別是輕量級、獨立的網路服務或將網路通訊功能整合到桌面程式中的絕佳選擇。

HttpListener C#(它對開發人員的作用:圖 1)

開發人員可以使用 HttpListener 設置 URI 前綴,以確定伺服器應監聽哪些地址。 一旦啟動監聽器,它會回應所有傳入的請求,並使用 HttpListenerContext 提供對請求和回應對象的訪問。 此配置使得可以創建符合應用程式需求的 HTTP 請求處理邏輯。 HttpListener 的使用方便性與適應性,使其在需要快速、有效且可配置的 HTTP 伺服器的情況下尤其有用。 HttpListener 提供了一個穩定且無額外負擔的解決方案,用於開發本地伺服器以進行測試,原型設計線上服務,或將通訊協定整合到桌面應用程式中。

HttpListener C# 的功能

C# 的 HttpListener 擁有多項功能,使其成為構建 HTTP 伺服器的有效工具。 基本要素包括:

易於使用:HttpListener 是一個易於使用的程式庫,讓程式設計師可以編寫較少的程式碼來建立基本的 HTTP 伺服器。

URI 首碼: 可以指定多個 URI 首碼以進行監聽,提供處理各種端點的靈活性,並保證伺服器僅對相關查詢作出回應。

非同步操作:HttpListener 支援非同步方法,透過高效處理大量請求,而不中斷主執行緒,提高伺服器的擴充性和回應能力。

身份驗證:您可以利用 HttpListener 對多種身份驗證技術的支援來保護所需的端點,例如基本、摘要、NTLM 和整合 Windows 驗證。

HTTPS 支援:HttpListener 可以設定為回應 HTTPS 請求,例如,啟用安全的客戶端-伺服器數據通信。

請求和回應處理:HttpListener 讓您能夠完全控制請求和回應過程,您可以通過添加新的標頭、狀態碼和內容類型來更改回應,並且可以讀取請求數據、標頭和參數。

監聽器配置:HttpListener 提供特定於監聽器的配置選項,以調整伺服器行為,例如證書管理(用於 HTTPS)、超時和其他參數。

日誌記錄和診斷:啟用日誌記錄和診斷,提供全面的請求和響應資訊,便於監控和故障排除。

相容性:允許與現有的 .NET 服務和應用程式順利整合,因為它可以與其他 .NET 元件和庫良好運作。

跨平台:HttpListener 兼容 Windows、Linux 和 macOS,可與 .NET Core 和 .NET 5+ 使用,提供跨平台的開發靈活性。

創建和配置 HttpListener C

在 C# 中创建和配置 HttpListener 涉及多个步骤。 以下是關於配置 HttpListener 以處理 HTTP 請求的詳細教學。

建立新的 .NET 專案

打開命令提示符、控制台或終端。

通過輸入啟動新創建的 .NET 主控台應用程式

dotnet new console -n HttplistenerExample
cd HttplistenerExample
dotnet new console -n HttplistenerExample
cd HttplistenerExample
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

創建一個 HttpListener 實例

首先,创建一个 HttpListener 类的实例。

配置 URI 前綴

新增 URI 前綴詞以指定聆聽者應處理哪些地址。

啟動監聽器

啟動 HttpListener 開始監聽傳入的 HTTP 請求。

處理傳入請求

創建一個循環來處理傳入的請求、處理它們並發送回應。

停止監聽器

在不再需要時優雅地停止 HttpListener。

以下是這些階段中實際應用的一個例子的說明:

using System;
using System.Net;
using System.Text;
class Program
{
    public static string url="http://localhost:8080/";
    public static HttpListener listener;
    public static void Main(string[] args)
    {
        // Step 1: Create an HttpListener instance
        listener = new HttpListener();
        // Step 2: Configure URI prefixes
        listener.Prefixes.Add(url);
        // Step 3: Start the listener
        listener.Start();
        Console.WriteLine("Listening for requests on "+url);
        // Step 4: Handle incoming requests
        // Wait for an incoming request
        while (true)
        {
            // getcontext method blocks
            HttpListenerContext context = listener.GetContext();
            HttpListenerRequest request = context.Request;
            // Process the request (e.g., log the request URL with or without query string)
            Console.WriteLine($"Received request for {request.Url}");
            // Create a response
            HttpListenerResponse response = context.Response;
            // add response info
            string responseString = "<html><body>Hello, world!</body></html>";
            byte[] buffer = Encoding.UTF8.GetBytes(responseString);
            // Set the content length and type
            response.ContentLength64 = buffer.Length;
            response.ContentType = "text/html";
            // Write the response to the output stream
            using (System.IO.Stream output = response.OutputStream)
            {
                output.Write(buffer, 0, buffer.Length);
            }
            // Close the response
            response.Close();
        }
        // Step 5: Stop the listener (this code is unreachable in the current loop structure)
        // listener.Stop();
    }
}
using System;
using System.Net;
using System.Text;
class Program
{
    public static string url="http://localhost:8080/";
    public static HttpListener listener;
    public static void Main(string[] args)
    {
        // Step 1: Create an HttpListener instance
        listener = new HttpListener();
        // Step 2: Configure URI prefixes
        listener.Prefixes.Add(url);
        // Step 3: Start the listener
        listener.Start();
        Console.WriteLine("Listening for requests on "+url);
        // Step 4: Handle incoming requests
        // Wait for an incoming request
        while (true)
        {
            // getcontext method blocks
            HttpListenerContext context = listener.GetContext();
            HttpListenerRequest request = context.Request;
            // Process the request (e.g., log the request URL with or without query string)
            Console.WriteLine($"Received request for {request.Url}");
            // Create a response
            HttpListenerResponse response = context.Response;
            // add response info
            string responseString = "<html><body>Hello, world!</body></html>";
            byte[] buffer = Encoding.UTF8.GetBytes(responseString);
            // Set the content length and type
            response.ContentLength64 = buffer.Length;
            response.ContentType = "text/html";
            // Write the response to the output stream
            using (System.IO.Stream output = response.OutputStream)
            {
                output.Write(buffer, 0, buffer.Length);
            }
            // Close the response
            response.Close();
        }
        // Step 5: Stop the listener (this code is unreachable in the current loop structure)
        // listener.Stop();
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

下面包含的 C# 代碼介紹了建立和配置 HttpListener 的過程,它作為一個基本的 HTTP 伺服器運作。 為了定義它將處理請求的位址,首先實例化一個 HttpListener 物件並附加一個 URI 前綴(http://localhost:8080/)。 接下來,使用 Start 方法來啟動監聽器。 我們使用不確定的 while 迴圈不斷監聽新的 HTTP 請求。 GetContext 在迴圈中等待請求,然後返回一個包含請求和響應物件的 HttpListenerContext 物件。

HttpListener C#(適用於開發者的工作原理):圖 2

在記錄請求 URL 之後,會建立一個簡單的 HTML 和回應物件,轉換成位元組陣列,然後發送到回應輸出流。 在將響應返回給客戶之前,會正確指定該響應的類型和持續時間。 迴圈意味著伺服器不斷處理請求,一個接著一個。 需要調用 halt 方法來停止請求控制台的監聽器,但在這種情況下,無限循環阻止其被達到。

HttpListener C#(對開發者的運作方式):圖 3

入門

IronPDF 可讓您在 .NET 中製作和更改高品質的 PDF 檔案,這是您創建文件和報告所需的。 HttpListener 的內建 HTTP 伺服器功能允許您在小型應用程式或服務中管理網路請求。 這兩個工具在各自的領域提高了 .NET 應用程序的實用性和速度。 要開始使用 C# 的 HttpListener 並將其與 IronPDF 整合以創建 PDF,請執行以下操作:

什麼是 IronPDF?

功能豐富的 .NET 庫IronPDF for C#允許 C# 程式生成、讀取和編輯 PDF 文檔。 藉由這個工具,開發者可以迅速將 HTML、CSS 和 JavaScript 資料轉換為高品質且可列印的 PDF。 在最關鍵的任務中,包括添加頁首和頁尾、拆分和合併PDF、為文檔添加水印以及將HTML轉換為PDF。 IronPDF 對於多種應用程序都很有幫助,因為它支持 .NET Framework 和 .NET Core。

由於 PDF 易於使用且包含大量資訊,開發人員可以輕鬆地將其納入產品中。 由於 IronPDF 能夠處理複雜的數據佈局和格式化,因此它生成的 PDF 輸出看起來非常像客戶端或原始的 HTML 文本。

IronPDF 在HTML 到 PDF轉換中表現優異,確保精確保留原始佈局和樣式。 它非常適合從基於網絡的內容(如報告、發票和文檔)創建PDF。 IronPDF 支援 HTML 檔案、URL 和原始 HTML 字串,輕鬆製作高品質的 PDF 文件。

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()

		' 1. Convert HTML String to PDF
		Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
		Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
		pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")

		' 2. Convert HTML File to PDF
		Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
		Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
		pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")

		' 3. Convert URL to PDF
		Dim url = "http://ironpdf.com" ' Specify the URL
		Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
		pdfFromUrl.SaveAs("URLToPDF.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

HttpListener C#(開發人員如何使用):圖 4

IronPDF 的功能

從 HTML 生成 PDF

將 JavaScript、HTML 和 CSS 轉換為 PDF。 IronPDF 支援媒體查詢和響應式設計,這兩個當代的網頁標準。 其對現代網頁標準的支持有助於用 HTML 和 CSS 動態裝飾 PDF 報告、發票和文件。

PDF 編輯

現有的 PDF 可以添加文字、圖片和其他內容。 使用 IronPDF,開發人員可以從 PDF 文件中提取文本和圖像,將多個 PDF 合併成一個文件,將 PDF 文件拆分為多個單獨的文檔,並在 PDF 頁面上加入水印、註釋、頁眉和頁腳。

PDF 轉換

將多種檔案格式,包括 Word、Excel 和圖片檔案,轉換為 PDF。 IronPDF 也支援將 PDF 轉換為圖像(PNG、JPEG 等)。

效能與可靠性

高性能和可靠性是工業環境中期望的設計特性。 開發人員可以輕鬆管理大型文件集。

安裝 IronPDF

若要獲取在 .NET 專案中處理 PDF 所需的工具,請安裝 IronPDF 套件。

dotnet add package IronPdf
dotnet add package IronPdf
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'dotnet add package IronPdf
$vbLabelText   $csharpLabel

將 HttpListener C# 與 IronPDF 整合

這是一個綜合示例,展示了如何使用 IronPDF 創建和提供 PDF 文件以及設置 HttpListener:

using System;
using System.Net;
using System.Text;
using IronPdf;
class Program
{
    static void Main(string[] args)
    {
        // Step 1: Create an HttpListener instance
        HttpListener listener = new HttpListener();
        // Step 2: Configure URI prefixes
        listener.Prefixes.Add("http://localhost:8080/");
        // Step 3: Start the listener
        listener.Start();
        Console.WriteLine("Listening for requests on http://localhost:8080/");
        // Step 4: Handle incoming requests
        while (true)
        {
            // Wait for an incoming request
            HttpListenerContext context = listener.GetContext();
            HttpListenerRequest request = context.Request;
            // Process the request (e.g., log the request URL)
            Console.WriteLine($"Received request for {request.Url}");
            // Generate PDF using IronPDF
            var htmlContent = "<h1>PDF generated by IronPDF</h1><p>This is a sample PDF document.</p>";
            var pdf = IronPdf.HtmlToPdf.StaticRenderHtmlAsPdf(htmlContent);
            // Get the PDF as a byte array
            byte[] pdfBytes = pdf.BinaryData;
            // Create a response
            HttpListenerResponse response = context.Response;
            // Set the content length and type
            response.ContentLength64 = pdfBytes.Length;
            response.ContentType = "application/pdf";
            // Write the PDF to the response output stream
            using (System.IO.Stream output = response.OutputStream)
            {
                output.Write(pdfBytes, 0, pdfBytes.Length);
            }
            // Close the response
            response.Close();
        }
        // Step 5: Stop the listener (this code is unreachable in the current loop structure)
        // listener.Stop();
    }
}
using System;
using System.Net;
using System.Text;
using IronPdf;
class Program
{
    static void Main(string[] args)
    {
        // Step 1: Create an HttpListener instance
        HttpListener listener = new HttpListener();
        // Step 2: Configure URI prefixes
        listener.Prefixes.Add("http://localhost:8080/");
        // Step 3: Start the listener
        listener.Start();
        Console.WriteLine("Listening for requests on http://localhost:8080/");
        // Step 4: Handle incoming requests
        while (true)
        {
            // Wait for an incoming request
            HttpListenerContext context = listener.GetContext();
            HttpListenerRequest request = context.Request;
            // Process the request (e.g., log the request URL)
            Console.WriteLine($"Received request for {request.Url}");
            // Generate PDF using IronPDF
            var htmlContent = "<h1>PDF generated by IronPDF</h1><p>This is a sample PDF document.</p>";
            var pdf = IronPdf.HtmlToPdf.StaticRenderHtmlAsPdf(htmlContent);
            // Get the PDF as a byte array
            byte[] pdfBytes = pdf.BinaryData;
            // Create a response
            HttpListenerResponse response = context.Response;
            // Set the content length and type
            response.ContentLength64 = pdfBytes.Length;
            response.ContentType = "application/pdf";
            // Write the PDF to the response output stream
            using (System.IO.Stream output = response.OutputStream)
            {
                output.Write(pdfBytes, 0, pdfBytes.Length);
            }
            // Close the response
            response.Close();
        }
        // Step 5: Stop the listener (this code is unreachable in the current loop structure)
        // listener.Stop();
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

所包含的 C# 代碼顯示瞭如何將IronPDF 的 HTML 到 PDF 轉換與 HttpListener 連接,以動態生成和傳送 PDF 文件,以及如何將其設置為基本的 HTTP 方法伺服器。 第一步是創建一個 HttpListener 的實例,並設置為在 http://localhost:8080/ 上接收 HTTP 請求。

啟動監聽器後,一個無限循環會負責處理傳入的請求。 該代碼記錄每個請求的請求 URL,使用 IronPDF 從 HTML 文本創建 PDF 文檔,然後將 PDF 轉換為位元組數組。 接下來,響應被設置為正確的 MIME 類型(application/pdf)和內容長度。

HttpListener C#(其對開發者的運作方式):圖5

在將 PDF 位元組陣列寫入響應輸出流後,關閉第一個響應流以將其發回給客戶端。 通過這種配置,伺服器可以有效地在回應 HTTP 請求時返回動態創建的 PDF 文件。

HttpListener C#(對開發人員的工作原理):圖 6

結論

總結來說,結合使用IronPDF和C#的HttpListener提供了一種可靠的方法來動態創建和通過HTTP傳送PDF文件。 藉助HttpListener,C#應用程式可以創建輕量級的HTTP伺服器,能夠處理進入的請求並提供靈活的響應生成。 透過使用 IronPDF 的動態 HTML 到 PDF 轉換功能,開發者可以直接從伺服器端邏輯有效地生成自訂或數據驅動的 PDF 報告、發票或其他文件。

需要透過網絡介面或 API 實時生成和傳送文件的應用程式可能會發現這種組合特別有用。 開發人員可以使用 HttpListener 和 IronPDF 實現可擴展和響應迅速的解決方案,以滿足特定的業務需求。 這些工具藉由促進文件在網路上的無縫生成和傳遞來增強用戶體驗。

您可以通過使用 OCR、處理條碼、創建 PDF、連接 Excel 等功能,來改善您的 .NET 開發工具箱。IronPDF 和 Iron Software Licensing Options 提供給開發者更完善的網頁應用程序和功能,並以更有效的開發方式進行,其起始價格為 $749。 它通過將其基本基礎與高度靈活的Iron Software套件和技術相結合來實現這一點。

透過明確列出專為專案量身定制的授權可能性,選擇最佳模型的過程將為開發人員簡化。 這些優勢讓開發人員能夠以有效、及時和協調的方式應用解決方案於各種問題。

Chipego
奇佩戈·卡林达
軟體工程師
Chipego 擁有天生的傾聽技能,這幫助他理解客戶問題,並提供智能解決方案。他在獲得信息技術理學學士學位後,于 2023 年加入 Iron Software 團隊。IronPDF 和 IronOCR 是 Chipego 專注的兩個產品,但隨著他每天找到新的方法來支持客戶,他對所有產品的了解也在不斷增長。他喜歡在 Iron Software 的協作生活,公司內的團隊成員從各自不同的經歷中共同努力,創造出有效的創新解決方案。當 Chipego 離開辦公桌時,他常常享受讀好書或踢足球的樂趣。
< 上一頁
Autofac C#(它如何為開發人員工作)
下一個 >
AutoFixture C#(開發人員的工作方式)