Wie man Logins und Authentifizierung mit C# verwaltet

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


Bewährte Verfahren

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

Hinweis: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

Bereit zu sehen, was Sie sonst noch tun können? Schauen Sie sich unsere Tutorial-Seite hier an: PDFs konvertieren

Häufig gestellte Fragen

Wie kann ich HTML in PDF konvertieren, ohne eine Login-Authentifizierung zu benötigen?

Um HTML ohne Login-Authentifizierung in PDF zu konvertieren, rendern Sie das HTML direkt aus einer Datei oder einem String mit IronPDF. Diese Methode umgeht die Notwendigkeit einer Authentifizierung vollständig.

Was sind die ersten Schritte, um HTML in C# in PDF zu konvertieren?

Beginnen Sie mit dem Herunterladen der C# IronPDF-Bibliothek von NuGet. Nach der Installation können Sie deren Methoden verwenden, um HTML-Dokumente direkt in PDFs zu rendern, selbst in Szenarien mit Login-Authentifizierung.

Welche Tools werden empfohlen, um HTML-Inhalte sicher für die PDF-Konvertierung herunterzuladen?

Verwenden Sie System.Net.WebClient oder HttpClient, um HTML-Inhalte und -Ressourcen wie Stylesheets und Bilder herunterzuladen. Diese Tools unterstützen Header und Logins. HtmlAgilityPack kann verwendet werden, um die Entdeckung von Ressourcen zu verwalten und sicherzustellen, dass alle notwendigen Ressourcen heruntergeladen werden.

Wie behandelt IronPDF die Netzwerk-Authentifizierung bei der Konvertierung von HTML in PDF?

IronPDF unterstützt die TLS-Netzwerk-Authentifizierung mit der LoginCredentials-Eigenschaft und bietet eine sichere Methode zur Handhabung der Authentifizierung in ASP.NET-Anwendungen.

Ist es möglich, HTML-Formular-Authentifizierung mit IronPDF durchzuführen?

Ja, Sie können die ChromeHttpLoginCredentials-Klasse von IronPDF verwenden, um die HTML-Formular-Authentifizierung zu handhaben. Stellen Sie sicher, dass die Anmeldedaten an die korrekte URL gesendet werden, wie im ACTION-Attribut des Formulars angegeben.

Wie kann ich die MVC-Login-Authentifizierung umgehen, wenn ich Ansichten in PDF konvertiere?

Sie können eine MVC-Ansicht programmatisch in einen String rendern, wodurch Sie MVC-Logins umgehen können und dennoch eine genaue Darstellung der Ansicht gewährleisten.

Welche Vorsichtsmaßnahmen sollten bei der Verwendung der HTML-Formular-Authentifizierung für die PDF-Konvertierung getroffen werden?

Stellen Sie sicher, dass alle Formulareingaben und Textbereiche korrekt im geposteten Datenmaterial unter Verwendung ihrer Namensattribute dargestellt werden. Beachten Sie, dass einige Websites Schutzmaßnahmen getroffen haben, um Maschinen-Logins zu verhindern.

Ist IronPDF vollständig kompatibel mit .NET 10, wenn Anmeldeinformationen zur Konvertierung geschützter URLs in PDF verwendet werden?

Ja – IronPDF unterstützt volle Kompatibilität mit .NET 10, einschließlich der Verwendung ChromeHttpLoginCredentials für die netzwerk- und formularbasierte Authentifizierung beim Rendern geschützter URLs in PDF.([ironpdf.com](https://ironpdf.com/blog/net-help/net-10-features/?utm_source=openai))

Curtis Chau
Technischer Autor

Curtis Chau hat einen Bachelor-Abschluss in Informatik von der Carleton University und ist spezialisiert auf Frontend-Entwicklung mit Expertise in Node.js, TypeScript, JavaScript und React. Leidenschaftlich widmet er sich der Erstellung intuitiver und ästhetisch ansprechender Benutzerschnittstellen und arbeitet gerne mit modernen Frameworks sowie der Erstellung gut strukturierter, optisch ansprechender ...

Weiterlesen
Bereit anzufangen?
Nuget Downloads 16,154,058 | Version: 2025.11 gerade veröffentlicht