如何使用 C# 管理登入和身份驗證

How to Convert HTML to PDF Behind Login Authentication

This article was translated from English: Does it need improvement?
Translated
View the article in English

The best way to deal with logins is to avoid them if possible and render HTML directly from a file or a string.

Quickstart: Convert HTML to PDF Behind Login with IronPDF

Easily convert HTML pages to PDFs, even when they're behind login forms, using IronPDF's simple and effective API. This quickstart guide shows you how to use the ChromeHttpLoginCredentials method to authenticate and retrieve protected content, ensuring a seamless conversion process. Whether you're dealing with network authentication or HTML form logins, IronPDF streamlines the process, saving you time and effort.

Nuget IconGet started making PDFs with NuGet now:

  1. Install IronPDF with NuGet Package Manager

    PM > Install-Package IronPdf

  2. Copy and run this code snippet.

    new ChromePdfRenderer { LoginCredentials = new ChromeHttpLoginCredentials("username","password") }
        .RenderUrlAsPdf("https://example.com/protected")
        .SaveAs("secure.pdf");
  3. Deploy to test on your live environment

    Start using IronPDF in your project today with a free trial
    arrow pointer


Best Practices

IronPDF supports TLS network authentication (username and password) and .NET web apps can easily support it: ChromeHttpLoginCredentials API

The best practice is to use System.Net.WebClient or HttpClient to download the HTML and any assets. This fully supports headers, logins, and everything else you may require. Once downloaded to memory or the disk, IronPDF can turn your HTML into a PDF. Assets such as stylesheets and images can be discovered using the HtmlAgilityPack and then downloaded using the System.Net.WebClient as well.

// Download HTML content from a URL
string html;
using (WebClient client = new WebClient()) 
{
    html = client.DownloadString("http://www.google.com");
}

// Load the HTML into an HtmlDocument
HtmlDocument doc = new HtmlDocument();        
doc.LoadHtml(html);

// Iterate through all image nodes and print their src attributes
foreach(HtmlNode img in doc.DocumentNode.SelectNodes("//img")) 
{
    Console.WriteLine(img.GetAttributeValue("src", null));
}
// Download HTML content from a URL
string html;
using (WebClient client = new WebClient()) 
{
    html = client.DownloadString("http://www.google.com");
}

// Load the HTML into an HtmlDocument
HtmlDocument doc = new HtmlDocument();        
doc.LoadHtml(html);

// Iterate through all image nodes and print their src attributes
foreach(HtmlNode img in doc.DocumentNode.SelectNodes("//img")) 
{
    Console.WriteLine(img.GetAttributeValue("src", null));
}
' Download HTML content from a URL
Dim html As String
Using client As New WebClient()
	html = client.DownloadString("http://www.google.com")
End Using

' Load the HTML into an HtmlDocument
Dim doc As New HtmlDocument()
doc.LoadHtml(html)

' Iterate through all image nodes and print their src attributes
For Each img As HtmlNode In doc.DocumentNode.SelectNodes("//img")
	Console.WriteLine(img.GetAttributeValue("src", Nothing))
Next img
$vbLabelText   $csharpLabel

請注意Any relative Url can be rebased to an absolute url using an overloaded constructor for the System.Uri class. To rebase any relative paths in an entire HTML document, add a <base> tag to the header using HtmlAgilityPack. Example.

Login using Network Authentication

Most ASP.NET applications support network authentication, which is more reliable than HTML form posting.

:path=/static-assets/pdf/content-code-examples/how-to/logins-username-password.cs
using IronPdf;
using System;

ChromePdfRenderer renderer = new ChromePdfRenderer
{
    // setting login credentials to bypass basic authentication
    LoginCredentials = new ChromeHttpLoginCredentials()
    {
        NetworkUsername = "testUser",
        NetworkPassword = "testPassword"
    }
};

var uri = new Uri("http://localhost:51169/Invoice");

// Render web URL to PDF
PdfDocument pdf = renderer.RenderUrlAsPdf(uri);

// Export PDF
pdf.SaveAs("UrlToPdfExample.Pdf");
Imports IronPdf
Imports System

Private renderer As New ChromePdfRenderer With {
	.LoginCredentials = New ChromeHttpLoginCredentials() With {
		.NetworkUsername = "testUser",
		.NetworkPassword = "testPassword"
	}
}

Private uri = New Uri("http://localhost:51169/Invoice")

' Render web URL to PDF
Private pdf As PdfDocument = renderer.RenderUrlAsPdf(uri)

' Export PDF
pdf.SaveAs("UrlToPdfExample.Pdf")
$vbLabelText   $csharpLabel

Login using an HTML Form

To log in by sending data to an HTML form may also be achieved using the ChromeHttpLoginCredentials class, as in the previous example. See IronPDF's ChromeHttpLoginCredentials API.

Please Consider:

  • The login data must be posted to the URL specified in the HTML form's ACTION attribute. This should be set as the *LoginFormUrl* attribute of the HttpLoginCredentials. This may vary from the URL you actually want to render as a PDF.
  • The data to be sent should represent every input and textarea in the HTML form. The name attributes define the name of each variable (not the id, as is commonly misunderstood).
  • Some websites may actively protect against this kind of machine login.

MVC

The following workaround allows a .NET MVC view to be rendered programmatically to a string, which is very useful in avoiding MVC logins yet rendering a view faithfully.

// Converts an MVC partial view to a string
public static string RenderPartialViewToString(this Controller controller, string viewPath, object model = null)
{
    try
    {
        // Set the model
        var context = controller.ControllerContext;
        controller.ViewData.Model = model;

        using (var sw = new StringWriter())
        {
            // Find the partial view
            var viewResult = ViewEngines.Engines.FindPartialView(context, viewPath);

            if (viewResult.View == null)
            {
                throw new Exception($"Partial view {viewPath} could not be found.");
            }

            // Create a view context
            var viewContext = new ViewContext(context, viewResult.View, context.Controller.ViewData, context.Controller.TempData, sw);

            // Render the view
            viewResult.View.Render(viewContext, sw);
            viewResult.ViewEngine.ReleaseView(context, viewResult.View);

            return sw.GetStringBuilder().ToString();
        }
    }
    catch (Exception ex)
    {
        // Return error message if there is an exception
        return ex.Message;
    }
}
// Converts an MVC partial view to a string
public static string RenderPartialViewToString(this Controller controller, string viewPath, object model = null)
{
    try
    {
        // Set the model
        var context = controller.ControllerContext;
        controller.ViewData.Model = model;

        using (var sw = new StringWriter())
        {
            // Find the partial view
            var viewResult = ViewEngines.Engines.FindPartialView(context, viewPath);

            if (viewResult.View == null)
            {
                throw new Exception($"Partial view {viewPath} could not be found.");
            }

            // Create a view context
            var viewContext = new ViewContext(context, viewResult.View, context.Controller.ViewData, context.Controller.TempData, sw);

            // Render the view
            viewResult.View.Render(viewContext, sw);
            viewResult.ViewEngine.ReleaseView(context, viewResult.View);

            return sw.GetStringBuilder().ToString();
        }
    }
    catch (Exception ex)
    {
        // Return error message if there is an exception
        return ex.Message;
    }
}
' Converts an MVC partial view to a string
<System.Runtime.CompilerServices.Extension> _
Public Function RenderPartialViewToString(ByVal controller As Controller, ByVal viewPath As String, Optional ByVal model As Object = Nothing) As String
	Try
		' Set the model
		Dim context = controller.ControllerContext
		controller.ViewData.Model = model

		Using sw = New StringWriter()
			' Find the partial view
			Dim viewResult = ViewEngines.Engines.FindPartialView(context, viewPath)

			If viewResult.View Is Nothing Then
				Throw New Exception($"Partial view {viewPath} could not be found.")
			End If

			' Create a view context
			Dim viewContext As New ViewContext(context, viewResult.View, context.Controller.ViewData, context.Controller.TempData, sw)

			' Render the view
			viewResult.View.Render(viewContext, sw)
			viewResult.ViewEngine.ReleaseView(context, viewResult.View)

			Return sw.GetStringBuilder().ToString()
		End Using
	Catch ex As Exception
		' Return error message if there is an exception
		Return ex.Message
	End Try
End Function
$vbLabelText   $csharpLabel

準備看看您還能做哪些其他事情嗎? 在這裡查看我們的教程頁面:轉換PDF

常見問題解答

如何在無需登入驗證的情況下將HTML轉換為PDF?

若要在無需登入驗證的情況下將 HTML 轉換為 PDF,可以使用 IronPDF 直接從檔案或字串渲染 HTML。此方法完全繞過了身份驗證的需要。

在 C# 中將 HTML 轉換為 PDF 的初始步驟是什麼?

首先從 NuGet 下載 C# IronPDF 庫。安裝完成後,您可以使用其方法直接將 HTML 文件渲染為 PDF,甚至可以處理需要登入驗證的場景。

推薦使用哪些工具安全地下載HTML內容以轉換為PDF?

使用 System.Net.WebClient 或 HttpClient 下載 HTML 內容以及樣式表和圖片等資源。這些工具支援標頭和登入資訊。 HtmlAgilityPack 可用於管理資源發現並確保下載所有必要的資源。

IronPDF 如何處理將 HTML 轉換為 PDF 的網頁驗證?

IronPDF 支援使用LoginCredentials屬性進行 TLS 網路驗證,為 ASP.NET 應用程式中的驗證提供了一種安全的方法。

是否可以使用 IronPDF 進行 HTML 表單驗證?

是的,您可以使用 IronPDF 的ChromeHttpLoginCredentials類別來處理 HTML 表單驗證。請確保登入資料提交至表單 ACTION 屬性中指定的正確 URL。

如何在將視圖轉換為 PDF 時繞過 MVC 登入驗證?

你可以透過程式設計方式將 MVC 視圖渲染成字串,這樣就可以繞過 MVC 登錄,同時確保視圖的準確渲染。

使用HTML表單驗證進行PDF轉換時應採取哪些預防措施?

請確保所有表單輸入框和文字區域都使用其名稱屬性正確顯示在提交的資料中。請注意,某些網站可能設有保護措施以防止機器登入。

使用登入憑證將受保護的 URL 轉換為 PDF 時,IronPDF 是否與 .NET 10 完全相容?

是的-IronPDF 完全相容於 .NET 10,包括在將受保護的 URL 呈現為 PDF 時使用ChromeHttpLoginCredentials進行網路和基於表單的身份驗證。 ([ironpdf.com](https://ironpdf.com/blog/net-help/net-10-features/?utm_source=openai))

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。

準備好開始了嗎?
Nuget 下載 16,154,058 | 版本: 2025.11 剛剛發布