Comment gérer les connexions et l'authentification en utilisant C#

Convertir HTML en PDF derrière l'authentification de connexion en C

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

Pour convertir du HTML en PDF derrière une authentification de connexion en C#, utilisez ChromeHttpLoginCredentials d'IronPDF pour l'authentification réseau ou téléchargez le HTML en utilisant System.Net.WebClient/HttpClient avant la conversion. Cette approche permet de gérer efficacement l'authentification réseau et les connexions par formulaire HTML.

as-heading:2(Démarrage rapide : Convertir du HTML en PDF (connexion requise) avec IronPDF)

Convertir des pages HTML en PDF derrière des formulaires de connexion à l'aide de l'API d'IronPDF. Ce guide présente ChromeHttpLoginCredentials pour l'authentification et la récupération de contenu protégé. Gérer à la fois l'authentification réseau et les connexions par formulaire HTML à l'aide d'exemples de code simples.

  1. Installez IronPDF avec le Gestionnaire de Packages NuGet

    PM > Install-Package IronPdf
  2. Copiez et exécutez cet extrait de code.

    new ChromePdfRenderer { LoginCredentials = new ChromeHttpLoginCredentials("username","password") }
        .RenderUrlAsPdf("https://example.com/protected")
        .SaveAs("secure.pdf");
  3. Déployez pour tester sur votre environnement de production.

    Commencez à utiliser IronPDF dans votre projet dès aujourd'hui avec un essai gratuit

    arrow pointer


Quelles sont les meilleures pratiques en matière d'authentification de connexion ?

IronPDF prend en charge l'authentification réseau TLS (nom d'utilisateur et mot de passe) par le biais de l'API ChromeHttpLoginCredentials API. Pour obtenir des conseils complets sur divers scénarios de connexion, consultez le tutoriel TLS Website & System Logins.

L'approche recommandée consiste à utiliser System.Net.WebClient ou HttpClient pour télécharger le code HTML et les ressources. Cette méthode prend en charge les en-têtes, les connexions et d'autres exigences. Après le téléchargement en mémoire ou sur disque, IronPDF convertit le HTML en PDF. Extrayez les ressources telles que les feuilles de style et les images en utilisant HtmlAgilityPack, puis téléchargez-les avec System.Net.WebClient.

// Download HTML content from a URL with authentication
string html;
using (WebClient client = new WebClient()) 
{
    // Add authentication headers if needed
    client.Headers.Add("Authorization", "Bearer " + accessToken);

    // Download the HTML string
    html = client.DownloadString("http://www.example.com/protected-content");
}

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

// Extract all image sources for downloading
foreach(HtmlNode img in doc.DocumentNode.SelectNodes("//img")) 
{
    string imgSrc = img.GetAttributeValue("src", null);
    Console.WriteLine($"Found image: {imgSrc}");

    // Download each image asset
    if (!string.IsNullOrEmpty(imgSrc))
    {
        string fileName = Path.GetFileName(imgSrc);
        client.DownloadFile(imgSrc, fileName);
    }
}

// Convert the downloaded HTML to PDF
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs("authenticated-content.pdf");
// Download HTML content from a URL with authentication
string html;
using (WebClient client = new WebClient()) 
{
    // Add authentication headers if needed
    client.Headers.Add("Authorization", "Bearer " + accessToken);

    // Download the HTML string
    html = client.DownloadString("http://www.example.com/protected-content");
}

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

// Extract all image sources for downloading
foreach(HtmlNode img in doc.DocumentNode.SelectNodes("//img")) 
{
    string imgSrc = img.GetAttributeValue("src", null);
    Console.WriteLine($"Found image: {imgSrc}");

    // Download each image asset
    if (!string.IsNullOrEmpty(imgSrc))
    {
        string fileName = Path.GetFileName(imgSrc);
        client.DownloadFile(imgSrc, fileName);
    }
}

// Convert the downloaded HTML to PDF
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs("authenticated-content.pdf");
Imports System.Net
Imports HtmlAgilityPack
Imports IronPdf

' Download HTML content from a URL with authentication
Dim html As String
Using client As New WebClient()
    ' Add authentication headers if needed
    client.Headers.Add("Authorization", "Bearer " & accessToken)

    ' Download the HTML string
    html = client.DownloadString("http://www.example.com/protected-content")
End Using

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

' Extract all image sources for downloading
For Each img As HtmlNode In doc.DocumentNode.SelectNodes("//img")
    Dim imgSrc As String = img.GetAttributeValue("src", Nothing)
    Console.WriteLine($"Found image: {imgSrc}")

    ' Download each image asset
    If Not String.IsNullOrEmpty(imgSrc) Then
        Dim fileName As String = Path.GetFileName(imgSrc)
        Using client As New WebClient()
            client.DownloadFile(imgSrc, fileName)
        End Using
    End If
Next

' Convert the downloaded HTML to PDF
Dim renderer As New ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlAsPdf(html)
pdf.SaveAs("authenticated-content.pdf")
$vbLabelText   $csharpLabel

Veuillez noterRebase les URL relatives en URL absolues en utilisant le constructeur surchargé System.Uri. Pour rebaser tous les chemins relatifs dans un document HTML, ajoutez une balise <base> à l'en-tête en utilisant HtmlAgilityPack. Exemple. Pour plus d'informations sur la gestion des URL et des ressources, consultez le guide URL de base et encodage des ressources .

Pourquoi télécharger d'abord le contenu HTML?

Le téléchargement du contenu HTML avant la conversion présente plusieurs avantages :

  1. Contrôle total : Modifiez le code HTML, corrigez les liens brisés ou injectez des jetons d'authentification avant la conversion
  2. Gestion des actifs : Télécharger et mettre en cache des ressources externes telles que des images, des fichiers CSS et JavaScript
  3. Flexibilité de l'authentification : Utilisez n'importe quel mécanisme d'authentification .NET, y compris OAuth, les jetons JWT ou les en-têtes personnalisés
  4. Performance : Mise en cache des contenus fréquemment consultés pour réduire la charge du serveur
  5. Débogage : Inspecter le code HTML exact qui est converti pour résoudre les problèmes

Pour les scénarios d'authentification complexes impliquant des cookies et des sessions, voir le guide Cookies qui explique la gestion de l'état d'authentification lors de la conversion PDF.

Comment gérer les ressources telles que les images et les feuilles de style?

Lors de la conversion de pages authentifiées, les ressources externes nécessitent souvent la même authentification. Voici une approche globale utilisant HttpClient :

public async Task<string> DownloadAuthenticatedHtmlWithAssets(string url, string authToken)
{
    using (var client = new HttpClient())
    {
        // Set authentication header
        client.DefaultRequestHeaders.Authorization = 
            new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", authToken);

        // Download the main HTML
        string html = await client.GetStringAsync(url);

        // Parse HTML to find assets
        var doc = new HtmlDocument();
        doc.LoadHtml(html);

        // Create a base URI for resolving relative paths
        var baseUri = new Uri(url);

        // Download CSS files
        var cssLinks = doc.DocumentNode.SelectNodes("//link[@rel='stylesheet']");
        if (cssLinks != null)
        {
            foreach (var link in cssLinks)
            {
                string href = link.GetAttributeValue("href", "");
                if (!string.IsNullOrEmpty(href))
                {
                    var cssUri = new Uri(baseUri, href);
                    string cssContent = await client.GetStringAsync(cssUri);

                    // Embed CSS directly in the HTML
                    var styleNode = doc.CreateElement("style");
                    styleNode.InnerHtml = cssContent;
                    doc.DocumentNode.SelectSingleNode("//head").AppendChild(styleNode);

                    // Remove the external link
                    link.Remove();
                }
            }
        }

        // Return the modified HTML with embedded assets
        return doc.DocumentNode.OuterHtml;
    }
}
public async Task<string> DownloadAuthenticatedHtmlWithAssets(string url, string authToken)
{
    using (var client = new HttpClient())
    {
        // Set authentication header
        client.DefaultRequestHeaders.Authorization = 
            new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", authToken);

        // Download the main HTML
        string html = await client.GetStringAsync(url);

        // Parse HTML to find assets
        var doc = new HtmlDocument();
        doc.LoadHtml(html);

        // Create a base URI for resolving relative paths
        var baseUri = new Uri(url);

        // Download CSS files
        var cssLinks = doc.DocumentNode.SelectNodes("//link[@rel='stylesheet']");
        if (cssLinks != null)
        {
            foreach (var link in cssLinks)
            {
                string href = link.GetAttributeValue("href", "");
                if (!string.IsNullOrEmpty(href))
                {
                    var cssUri = new Uri(baseUri, href);
                    string cssContent = await client.GetStringAsync(cssUri);

                    // Embed CSS directly in the HTML
                    var styleNode = doc.CreateElement("style");
                    styleNode.InnerHtml = cssContent;
                    doc.DocumentNode.SelectSingleNode("//head").AppendChild(styleNode);

                    // Remove the external link
                    link.Remove();
                }
            }
        }

        // Return the modified HTML with embedded assets
        return doc.DocumentNode.OuterHtml;
    }
}
Imports System
Imports System.Net.Http
Imports System.Threading.Tasks
Imports HtmlAgilityPack

Public Class HtmlDownloader
    Public Async Function DownloadAuthenticatedHtmlWithAssets(url As String, authToken As String) As Task(Of String)
        Using client As New HttpClient()
            ' Set authentication header
            client.DefaultRequestHeaders.Authorization = New System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", authToken)

            ' Download the main HTML
            Dim html As String = Await client.GetStringAsync(url)

            ' Parse HTML to find assets
            Dim doc As New HtmlDocument()
            doc.LoadHtml(html)

            ' Create a base URI for resolving relative paths
            Dim baseUri As New Uri(url)

            ' Download CSS files
            Dim cssLinks = doc.DocumentNode.SelectNodes("//link[@rel='stylesheet']")
            If cssLinks IsNot Nothing Then
                For Each link In cssLinks
                    Dim href As String = link.GetAttributeValue("href", "")
                    If Not String.IsNullOrEmpty(href) Then
                        Dim cssUri As New Uri(baseUri, href)
                        Dim cssContent As String = Await client.GetStringAsync(cssUri)

                        ' Embed CSS directly in the HTML
                        Dim styleNode = doc.CreateElement("style")
                        styleNode.InnerHtml = cssContent
                        doc.DocumentNode.SelectSingleNode("//head").AppendChild(styleNode)

                        ' Remove the external link
                        link.Remove()
                    End If
                Next
            End If

            ' Return the modified HTML with embedded assets
            Return doc.DocumentNode.OuterHtml
        End Using
    End Function
End Class
$vbLabelText   $csharpLabel

Quels sont les outils qui aident à l'analyse HTML ?

La bibliothèque HtmlAgilityPack est la bibliothèque d'analyse HTML la plus populaire pour .NET, mais il existe des alternatives :

  1. HtmlAgilityPack : le meilleur pour l'analyse et la manipulation HTML en général
  2. AngleSharp : Analyseur HTML moderne, conforme aux normes, avec prise en charge des sélecteurs CSS
  3. CsQuery : syntaxe similaire à jQuery pour les développeurs C# familiarisés avec jQuery
  4. Expressions régulières : Pour les tâches d'extraction simples (non recommandées pour le HTML complexe)

Comment se connecter à l'aide de l'authentification réseau?

La plupart des applications ASP.NET prennent en charge l'authentification réseau, qui est plus fiable que l'envoi de formulaires HTML. IronPDF fournit une prise en charge intégrée de l'authentification de base, digest et NTLM via la classe ChromeHttpLoginCredentials. Pour une personnalisation supplémentaire des en-têtes, consultez le guide des en-têtes de requête HTTP.

: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

Pourquoi l'authentification par réseau est-elle plus fiable que l'envoi de formulaires ?

L'authentification en réseau offre plusieurs avantages par rapport à l'affichage de formulaires HTML :

  1. Protocole normalisé : Utilise les en-têtes d'authentification HTTP conformément aux normes RFC
  2. Intégration du navigateur : Le moteur de rendu de Chrome gère l'authentification de manière transparente
  3. Gestion de session : Traitement automatique des défis d'authentification et de la persistance des sessions
  4. Sécurité : Les informations d'identification sont transmises de manière sécurisée via les en-têtes plutôt que via les données du formulaire
  5. Compatibilité : Fonctionne avec la plupart des systèmes d'authentification d'entreprise (Active Directory, LDAP)

Quelles sont les informations d'identification dont j'ai besoin pour l'authentification réseau ?

Les différents types d'authentification requièrent des informations d'identification différentes :

// Basic Authentication (most common)
var basicAuth = new ChromeHttpLoginCredentials
{
    NetworkUsername = "user@domain.com",
    NetworkPassword = "password123",
    AuthenticationType = ChromeHttpLoginCredentials.AuthType.Basic
};

// NTLM/Windows Authentication
var ntlmAuth = new ChromeHttpLoginCredentials
{
    NetworkUsername = "DOMAIN\\username", // Include domain
    NetworkPassword = "password123",
    AuthenticationType = ChromeHttpLoginCredentials.AuthType.Ntlm
};

// Custom authentication headers
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.CustomHttpHeaders.Add("X-API-Key", "your-api-key");
renderer.RenderingOptions.CustomHttpHeaders.Add("Authorization", "Bearer " + jwtToken);
// Basic Authentication (most common)
var basicAuth = new ChromeHttpLoginCredentials
{
    NetworkUsername = "user@domain.com",
    NetworkPassword = "password123",
    AuthenticationType = ChromeHttpLoginCredentials.AuthType.Basic
};

// NTLM/Windows Authentication
var ntlmAuth = new ChromeHttpLoginCredentials
{
    NetworkUsername = "DOMAIN\\username", // Include domain
    NetworkPassword = "password123",
    AuthenticationType = ChromeHttpLoginCredentials.AuthType.Ntlm
};

// Custom authentication headers
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.CustomHttpHeaders.Add("X-API-Key", "your-api-key");
renderer.RenderingOptions.CustomHttpHeaders.Add("Authorization", "Bearer " + jwtToken);
Imports System.Collections.Generic

' Basic Authentication (most common)
Dim basicAuth As New ChromeHttpLoginCredentials With {
    .NetworkUsername = "user@domain.com",
    .NetworkPassword = "password123",
    .AuthenticationType = ChromeHttpLoginCredentials.AuthType.Basic
}

' NTLM/Windows Authentication
Dim ntlmAuth As New ChromeHttpLoginCredentials With {
    .NetworkUsername = "DOMAIN\username", ' Include domain
    .NetworkPassword = "password123",
    .AuthenticationType = ChromeHttpLoginCredentials.AuthType.Ntlm
}

' Custom authentication headers
Dim renderer As New ChromePdfRenderer()
renderer.RenderingOptions.CustomHttpHeaders.Add("X-API-Key", "your-api-key")
renderer.RenderingOptions.CustomHttpHeaders.Add("Authorization", "Bearer " & jwtToken)
$vbLabelText   $csharpLabel

Comment dépanner les échecs d'authentification?

Problèmes d'authentification courants et solutions :

  1. 401 Non autorisé : Vérifier les informations d'identification et le type d'authentification
  2. 403 Forbidden : L'utilisateur est authentifié mais n'a pas les autorisations nécessaires
  3. Erreurs de délai d'attente : Augmenter la valeur de RenderDelay pour les systèmes d'authentification lents
  4. Erreurs de certificat : Configurer les paramètres TLS/SSL de manière appropriée

Permettre le débogage pour diagnostiquer les problèmes :

// Enable detailed logging
IronPdf.Logging.Logger.EnableDebugging = true;
IronPdf.Logging.Logger.LogFilePath = "IronPdf.log";
IronPdf.Logging.Logger.LoggingMode = IronPdf.Logging.Logger.LoggingModes.All;

// Test authentication
try 
{
    var pdf = renderer.RenderUrlAsPdf("https://secure.example.com");
    pdf.SaveAs("authenticated.pdf");
}
catch (Exception ex)
{
    Console.WriteLine($"Authentication failed: {ex.Message}");
    // Check IronPdf.log for detailed error information
}
// Enable detailed logging
IronPdf.Logging.Logger.EnableDebugging = true;
IronPdf.Logging.Logger.LogFilePath = "IronPdf.log";
IronPdf.Logging.Logger.LoggingMode = IronPdf.Logging.Logger.LoggingModes.All;

// Test authentication
try 
{
    var pdf = renderer.RenderUrlAsPdf("https://secure.example.com");
    pdf.SaveAs("authenticated.pdf");
}
catch (Exception ex)
{
    Console.WriteLine($"Authentication failed: {ex.Message}");
    // Check IronPdf.log for detailed error information
}
Imports IronPdf
Imports System

' Enable detailed logging
Logging.Logger.EnableDebugging = True
Logging.Logger.LogFilePath = "IronPdf.log"
Logging.Logger.LoggingMode = Logging.Logger.LoggingModes.All

' Test authentication
Try
    Dim pdf = renderer.RenderUrlAsPdf("https://secure.example.com")
    pdf.SaveAs("authenticated.pdf")
Catch ex As Exception
    Console.WriteLine($"Authentication failed: {ex.Message}")
    ' Check IronPdf.log for detailed error information
End Try
$vbLabelText   $csharpLabel

Comment se connecter à l'aide d'un formulaire HTML?

Pour se connecter en envoyant des données à un formulaire HTML, utilisez la classe ChromeHttpLoginCredentials. Voir l'API d'IronPDF ChromeHttpLoginCredentials API.

Considérez les points suivants:

  • Publier les données de connexion à l'URL spécifiée dans l'attribut ACTION du formulaire HTML. Définissez ceci comme l'attribut LoginFormUrl de HttpLoginCredentials. Cette traduction peut être différente de l'URL que vous souhaitez rendre au format PDF.
  • Envoyer des données représentant chaque entrée et zone de texte dans le formulaire HTML. Les attributs name définissent le nom de chaque variable (pas l'id).
  • Certains sites web se protègent activement contre la connexion automatique.

Voici un exemple complet d'authentification par formulaire :

// Configure form-based login
var formLogin = new ChromeHttpLoginCredentials
{
    LoginFormUrl = "https://example.com/login",
    LoginFormData = new Dictionary<string, string>
    {
        {"username", "user@example.com"},
        {"password", "securePassword123"},
        {"rememberMe", "true"},
        {"csrf_token", "abc123"} // Include any hidden fields
    }
};

var renderer = new ChromePdfRenderer
{
    LoginCredentials = formLogin,
    RenderingOptions = new ChromePdfRenderOptions
    {
        RenderDelay = 3000, // Allow time for login redirect
        EnableJavaScript = true
    }
};

// The actual page you want to convert (after login)
var pdf = renderer.RenderUrlAsPdf("https://example.com/dashboard");
pdf.SaveAs("dashboard.pdf");
// Configure form-based login
var formLogin = new ChromeHttpLoginCredentials
{
    LoginFormUrl = "https://example.com/login",
    LoginFormData = new Dictionary<string, string>
    {
        {"username", "user@example.com"},
        {"password", "securePassword123"},
        {"rememberMe", "true"},
        {"csrf_token", "abc123"} // Include any hidden fields
    }
};

var renderer = new ChromePdfRenderer
{
    LoginCredentials = formLogin,
    RenderingOptions = new ChromePdfRenderOptions
    {
        RenderDelay = 3000, // Allow time for login redirect
        EnableJavaScript = true
    }
};

// The actual page you want to convert (after login)
var pdf = renderer.RenderUrlAsPdf("https://example.com/dashboard");
pdf.SaveAs("dashboard.pdf");
Imports System.Collections.Generic

' Configure form-based login
Dim formLogin As New ChromeHttpLoginCredentials With {
    .LoginFormUrl = "https://example.com/login",
    .LoginFormData = New Dictionary(Of String, String) From {
        {"username", "user@example.com"},
        {"password", "securePassword123"},
        {"rememberMe", "true"},
        {"csrf_token", "abc123"} ' Include any hidden fields
    }
}

Dim renderer As New ChromePdfRenderer With {
    .LoginCredentials = formLogin,
    .RenderingOptions = New ChromePdfRenderOptions With {
        .RenderDelay = 3000, ' Allow time for login redirect
        .EnableJavaScript = True
    }
}

' The actual page you want to convert (after login)
Dim pdf = renderer.RenderUrlAsPdf("https://example.com/dashboard")
pdf.SaveAs("dashboard.pdf")
$vbLabelText   $csharpLabel

Quelles données de formulaire dois-je capturer ?

Pour une authentification réussie via des formulaires HTML, saisissez toutes les entrées du formulaire :

// Use this helper method to extract form fields
public Dictionary<string, string> ExtractFormFields(string loginPageHtml)
{
    var formData = new Dictionary<string, string>();
    var doc = new HtmlDocument();
    doc.LoadHtml(loginPageHtml);

    // Find all input fields
    var inputs = doc.DocumentNode.SelectNodes("//input");
    if (inputs != null)
    {
        foreach (var input in inputs)
        {
            string name = input.GetAttributeValue("name", "");
            string value = input.GetAttributeValue("value", "");
            string type = input.GetAttributeValue("type", "text");

            if (!string.IsNullOrEmpty(name))
            {
                // Handle different input types
                switch (type.ToLower())
                {
                    case "checkbox":
                        if (input.Attributes["checked"] != null)
                            formData[name] = "on";
                        break;
                    case "radio":
                        if (input.Attributes["checked"] != null)
                            formData[name] = value;
                        break;
                    default:
                        formData[name] = value;
                        break;
                }
            }
        }
    }

    // Don't forget select elements
    var selects = doc.DocumentNode.SelectNodes("//select");
    if (selects != null)
    {
        foreach (var select in selects)
        {
            string name = select.GetAttributeValue("name", "");
            var selected = select.SelectSingleNode(".//option[@selected]");
            if (selected != null && !string.IsNullOrEmpty(name))
            {
                formData[name] = selected.GetAttributeValue("value", "");
            }
        }
    }

    return formData;
}
// Use this helper method to extract form fields
public Dictionary<string, string> ExtractFormFields(string loginPageHtml)
{
    var formData = new Dictionary<string, string>();
    var doc = new HtmlDocument();
    doc.LoadHtml(loginPageHtml);

    // Find all input fields
    var inputs = doc.DocumentNode.SelectNodes("//input");
    if (inputs != null)
    {
        foreach (var input in inputs)
        {
            string name = input.GetAttributeValue("name", "");
            string value = input.GetAttributeValue("value", "");
            string type = input.GetAttributeValue("type", "text");

            if (!string.IsNullOrEmpty(name))
            {
                // Handle different input types
                switch (type.ToLower())
                {
                    case "checkbox":
                        if (input.Attributes["checked"] != null)
                            formData[name] = "on";
                        break;
                    case "radio":
                        if (input.Attributes["checked"] != null)
                            formData[name] = value;
                        break;
                    default:
                        formData[name] = value;
                        break;
                }
            }
        }
    }

    // Don't forget select elements
    var selects = doc.DocumentNode.SelectNodes("//select");
    if (selects != null)
    {
        foreach (var select in selects)
        {
            string name = select.GetAttributeValue("name", "");
            var selected = select.SelectSingleNode(".//option[@selected]");
            if (selected != null && !string.IsNullOrEmpty(name))
            {
                formData[name] = selected.GetAttributeValue("value", "");
            }
        }
    }

    return formData;
}
Imports HtmlAgilityPack

Public Function ExtractFormFields(loginPageHtml As String) As Dictionary(Of String, String)
    Dim formData As New Dictionary(Of String, String)()
    Dim doc As New HtmlDocument()
    doc.LoadHtml(loginPageHtml)

    ' Find all input fields
    Dim inputs = doc.DocumentNode.SelectNodes("//input")
    If inputs IsNot Nothing Then
        For Each input In inputs
            Dim name As String = input.GetAttributeValue("name", "")
            Dim value As String = input.GetAttributeValue("value", "")
            Dim type As String = input.GetAttributeValue("type", "text")

            If Not String.IsNullOrEmpty(name) Then
                ' Handle different input types
                Select Case type.ToLower()
                    Case "checkbox"
                        If input.Attributes("checked") IsNot Nothing Then
                            formData(name) = "on"
                        End If
                    Case "radio"
                        If input.Attributes("checked") IsNot Nothing Then
                            formData(name) = value
                        End If
                    Case Else
                        formData(name) = value
                End Select
            End If
        Next
    End If

    ' Don't forget select elements
    Dim selects = doc.DocumentNode.SelectNodes("//select")
    If selects IsNot Nothing Then
        For Each selectNode In selects
            Dim name As String = selectNode.GetAttributeValue("name", "")
            Dim selected = selectNode.SelectSingleNode(".//option[@selected]")
            If selected IsNot Nothing AndAlso Not String.IsNullOrEmpty(name) Then
                formData(name) = selected.GetAttributeValue("value", "")
            End If
        Next
    End If

    Return formData
End Function
$vbLabelText   $csharpLabel

Comment trouver l'URL correcte de l'action du formulaire?

L'URL de l'action du formulaire est essentielle pour une authentification réussie :

public string ExtractFormAction(string loginPageUrl, string loginPageHtml)
{
    var doc = new HtmlDocument();
    doc.LoadHtml(loginPageHtml);

    // Find the login form
    var form = doc.DocumentNode.SelectSingleNode("//form[contains(@action, 'login') or contains(@id, 'login') or contains(@class, 'login')]");

    if (form == null)
    {
        // Try finding any form with password field
        form = doc.DocumentNode.SelectSingleNode("//form[.//input[@type='password']]");
    }

    if (form != null)
    {
        string action = form.GetAttributeValue("action", "");

        // Resolve relative URLs
        if (!string.IsNullOrEmpty(action))
        {
            var baseUri = new Uri(loginPageUrl);
            var actionUri = new Uri(baseUri, action);
            return actionUri.ToString();
        }
    }

    // Default to the login page URL if no action found
    return loginPageUrl;
}
public string ExtractFormAction(string loginPageUrl, string loginPageHtml)
{
    var doc = new HtmlDocument();
    doc.LoadHtml(loginPageHtml);

    // Find the login form
    var form = doc.DocumentNode.SelectSingleNode("//form[contains(@action, 'login') or contains(@id, 'login') or contains(@class, 'login')]");

    if (form == null)
    {
        // Try finding any form with password field
        form = doc.DocumentNode.SelectSingleNode("//form[.//input[@type='password']]");
    }

    if (form != null)
    {
        string action = form.GetAttributeValue("action", "");

        // Resolve relative URLs
        if (!string.IsNullOrEmpty(action))
        {
            var baseUri = new Uri(loginPageUrl);
            var actionUri = new Uri(baseUri, action);
            return actionUri.ToString();
        }
    }

    // Default to the login page URL if no action found
    return loginPageUrl;
}
Imports System

Public Function ExtractFormAction(loginPageUrl As String, loginPageHtml As String) As String
    Dim doc As New HtmlDocument()
    doc.LoadHtml(loginPageHtml)

    ' Find the login form
    Dim form = doc.DocumentNode.SelectSingleNode("//form[contains(@action, 'login') or contains(@id, 'login') or contains(@class, 'login')]")

    If form Is Nothing Then
        ' Try finding any form with password field
        form = doc.DocumentNode.SelectSingleNode("//form[.//input[@type='password']]")
    End If

    If form IsNot Nothing Then
        Dim action As String = form.GetAttributeValue("action", "")

        ' Resolve relative URLs
        If Not String.IsNullOrEmpty(action) Then
            Dim baseUri As New Uri(loginPageUrl)
            Dim actionUri As New Uri(baseUri, action)
            Return actionUri.ToString()
        End If
    End If

    ' Default to the login page URL if no action found
    Return loginPageUrl
End Function
$vbLabelText   $csharpLabel

Quels sont les problèmes courants liés à l'authentification par formulaire ?

  1. Tokens CSRF : De nombreux formulaires incluent des jetons anti-falsification qui expirent
  2. Validation JavaScript : Certains formulaires nécessitent l'exécution de JavaScript
  3. Authentification en plusieurs étapes : Formulaires nécessitant plusieurs pages
  4. CAPTCHA Protection : les défis de la vérification humaine
  5. Délais de session : Des sessions de connexion qui expirent rapidement

Comment gérer la protection anti-bots?

Les sites web modernes mettent en place une protection contre les connexions automatisées :

// Strategies for handling anti-bot measures
var renderer = new ChromePdfRenderer
{
    RenderingOptions = new ChromePdfRenderOptions
    {
        // Mimic real browser behavior
        ViewPortWidth = 1920,
        ViewPortHeight = 1080,
        EnableJavaScript = true,
        RenderDelay = 5000, // Wait for JavaScript

        // Set a real user agent
        CustomHttpHeaders = new Dictionary<string, string>
        {
            {"User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}
        }
    }
};

 // For sites with rate limiting, add delays between requests
 System.Threading.Thread.Sleep(2000);
// Strategies for handling anti-bot measures
var renderer = new ChromePdfRenderer
{
    RenderingOptions = new ChromePdfRenderOptions
    {
        // Mimic real browser behavior
        ViewPortWidth = 1920,
        ViewPortHeight = 1080,
        EnableJavaScript = true,
        RenderDelay = 5000, // Wait for JavaScript

        // Set a real user agent
        CustomHttpHeaders = new Dictionary<string, string>
        {
            {"User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}
        }
    }
};

 // For sites with rate limiting, add delays between requests
 System.Threading.Thread.Sleep(2000);
' Strategies for handling anti-bot measures
Dim renderer = New ChromePdfRenderer With {
    .RenderingOptions = New ChromePdfRenderOptions With {
        ' Mimic real browser behavior
        .ViewPortWidth = 1920,
        .ViewPortHeight = 1080,
        .EnableJavaScript = True,
        .RenderDelay = 5000, ' Wait for JavaScript

        ' Set a real user agent
        .CustomHttpHeaders = New Dictionary(Of String, String) From {
            {"User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}
        }
    }
}

' For sites with rate limiting, add delays between requests
System.Threading.Thread.Sleep(2000)
$vbLabelText   $csharpLabel

Pour obtenir des conseils complets sur la conversion de HTML en PDF, y compris des scénarios d'authentification complexes, consultez le tutoriel HTML en PDF.

Comment gérer l'authentification MVC?

La solution suivante permet de rendre une vue MVC .NET en une chaîne de caractères de manière programmatique, en évitant les connexions MVC tout en rendant les vues fidèlement. Cette approche fonctionne bien lors de la conversion de CSHTML en PDF dans MVC Core ou MVC Framework.

// 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;
    }
}

// Usage in an MVC Controller
public ActionResult GeneratePdf()
{
    // Render authenticated view to string
    var model = new InvoiceViewModel { /* populate model */ };
    string html = this.RenderPartialViewToString("~/Views/Invoice/Details.cshtml", model);

    // Convert to PDF
    var renderer = new ChromePdfRenderer();
    var pdf = renderer.RenderHtmlAsPdf(html);

    // Return PDF file
    return File(pdf.BinaryData, "application/pdf", "invoice.pdf");
}
// 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;
    }
}

// Usage in an MVC Controller
public ActionResult GeneratePdf()
{
    // Render authenticated view to string
    var model = new InvoiceViewModel { /* populate model */ };
    string html = this.RenderPartialViewToString("~/Views/Invoice/Details.cshtml", model);

    // Convert to PDF
    var renderer = new ChromePdfRenderer();
    var pdf = renderer.RenderHtmlAsPdf(html);

    // Return PDF file
    return File(pdf.BinaryData, "application/pdf", "invoice.pdf");
}
Imports System
Imports System.IO
Imports System.Web.Mvc
Imports IronPdf

' Converts an MVC partial view to a string
Public Module ControllerExtensions
    <System.Runtime.CompilerServices.Extension>
    Public Function RenderPartialViewToString(controller As Controller, viewPath As String, Optional model As Object = Nothing) As String
        Try
            ' Set the model
            Dim context = controller.ControllerContext
            controller.ViewData.Model = model

            Using sw As 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
End Module

' Usage in an MVC Controller
Public Class InvoiceController
    Inherits Controller

    Public Function GeneratePdf() As ActionResult
        ' Render authenticated view to string
        Dim model As New InvoiceViewModel() ' populate model
        Dim html As String = Me.RenderPartialViewToString("~/Views/Invoice/Details.cshtml", model)

        ' Convert to PDF
        Dim renderer As New ChromePdfRenderer()
        Dim pdf = renderer.RenderHtmlAsPdf(html)

        ' Return PDF file
        Return File(pdf.BinaryData, "application/pdf", "invoice.pdf")
    End Function
End Class
$vbLabelText   $csharpLabel

Pourquoi convertir les vues en chaînes au lieu de les convertir directement ?

Le rendu des vues MVC sous forme de chaînes de caractères présente plusieurs avantages clés :

  1. Contexte d'authentification : Les vues sont affichées dans le contexte de l'utilisateur authentifié
  2. Pipeline MVC complet : Toutes les fonctionnalités MVC fonctionnent, y compris les helpers ViewBag, TempData et Html
  3. Prise en charge des mises en page : Les pages maîtresses et les mises en page s'affichent correctement
  4. Model Binding : Des modèles de vue complexes fonctionnent de manière transparente
  5. Filtres d'action : les filtres de sécurité et de journalisation s'exécutent normalement

Quels sont les avantages de cette solution de contournement MVC?

L'approche de rendu de chaîne MVC offre :

  • Sécurité : pas besoin d'exposer les URL internes ou de contourner l'authentification
  • Performance : Éviter les requêtes HTTP supplémentaires
  • Cohérence : résultat identique à ce que les utilisateurs voient dans les navigateurs
  • Flexibilité : Modifier le code HTML avant la conversion en PDF
  • Testing : Génération de tests unitaires HTML en toute simplicité

Comment passer des modèles à la vue rendue?

Voici un exemple complet avec un modèle complexe :

public class InvoiceController : Controller
{
    private readonly IInvoiceService _invoiceService;

    public async Task<ActionResult> DownloadInvoicePdf(int invoiceId)
    {
        // Load data within authenticated context
        var invoice = await _invoiceService.GetInvoiceAsync(invoiceId);

        if (invoice == null || invoice.UserId != User.Identity.GetUserId())
        {
            return HttpNotFound();
        }

        // Create view model
        var viewModel = new InvoiceDetailsViewModel
        {
            Invoice = invoice,
            Company = await _invoiceService.GetCompanyDetailsAsync(),
            LineItems = await _invoiceService.GetLineItemsAsync(invoiceId),
            TaxDetails = await _invoiceService.GetTaxDetailsAsync(invoiceId)
        };

        // Render to HTML string
        string html = this.RenderPartialViewToString("~/Views/Invoice/DetailsPdf.cshtml", viewModel);

        // Add custom styling for PDF
        html = $@"
            <html>
            <head>
                <style>
                    body {{ font-family: Arial, sans-serif; }}
                    .invoice-header {{ background-color: #f0f0f0; padding: 20px; }}
                    .line-items {{ width: 100%; border-collapse: collapse; }}
                    .line-items th, .line-items td {{ border: 1px solid #ddd; padding: 8px; }}
                </style>
            </head>
            <body>
                {html}
            </body>
            </html>";

        // Convert to PDF with options
        var renderer = new ChromePdfRenderer
        {
            RenderingOptions = new ChromePdfRenderOptions
            {
                MarginTop = 20,
                MarginBottom = 20,
                MarginLeft = 10,
                MarginRight = 10,
                PrintHtmlBackgrounds = true
            }
        };

        var pdf = renderer.RenderHtmlAsPdf(html);

        // Add metadata
        pdf.MetaData.Author = "Invoice System";
        pdf.MetaData.Title = $"Invoice #{invoice.Number}";
        pdf.MetaData.CreationDate = DateTime.Now;

        return File(pdf.BinaryData, "application/pdf", $"Invoice-{invoice.Number}.pdf");
    }
}
public class InvoiceController : Controller
{
    private readonly IInvoiceService _invoiceService;

    public async Task<ActionResult> DownloadInvoicePdf(int invoiceId)
    {
        // Load data within authenticated context
        var invoice = await _invoiceService.GetInvoiceAsync(invoiceId);

        if (invoice == null || invoice.UserId != User.Identity.GetUserId())
        {
            return HttpNotFound();
        }

        // Create view model
        var viewModel = new InvoiceDetailsViewModel
        {
            Invoice = invoice,
            Company = await _invoiceService.GetCompanyDetailsAsync(),
            LineItems = await _invoiceService.GetLineItemsAsync(invoiceId),
            TaxDetails = await _invoiceService.GetTaxDetailsAsync(invoiceId)
        };

        // Render to HTML string
        string html = this.RenderPartialViewToString("~/Views/Invoice/DetailsPdf.cshtml", viewModel);

        // Add custom styling for PDF
        html = $@"
            <html>
            <head>
                <style>
                    body {{ font-family: Arial, sans-serif; }}
                    .invoice-header {{ background-color: #f0f0f0; padding: 20px; }}
                    .line-items {{ width: 100%; border-collapse: collapse; }}
                    .line-items th, .line-items td {{ border: 1px solid #ddd; padding: 8px; }}
                </style>
            </head>
            <body>
                {html}
            </body>
            </html>";

        // Convert to PDF with options
        var renderer = new ChromePdfRenderer
        {
            RenderingOptions = new ChromePdfRenderOptions
            {
                MarginTop = 20,
                MarginBottom = 20,
                MarginLeft = 10,
                MarginRight = 10,
                PrintHtmlBackgrounds = true
            }
        };

        var pdf = renderer.RenderHtmlAsPdf(html);

        // Add metadata
        pdf.MetaData.Author = "Invoice System";
        pdf.MetaData.Title = $"Invoice #{invoice.Number}";
        pdf.MetaData.CreationDate = DateTime.Now;

        return File(pdf.BinaryData, "application/pdf", $"Invoice-{invoice.Number}.pdf");
    }
}
Imports System.Threading.Tasks
Imports System.Web.Mvc

Public Class InvoiceController
    Inherits Controller

    Private ReadOnly _invoiceService As IInvoiceService

    Public Async Function DownloadInvoicePdf(invoiceId As Integer) As Task(Of ActionResult)
        ' Load data within authenticated context
        Dim invoice = Await _invoiceService.GetInvoiceAsync(invoiceId)

        If invoice Is Nothing OrElse invoice.UserId <> User.Identity.GetUserId() Then
            Return HttpNotFound()
        End If

        ' Create view model
        Dim viewModel As New InvoiceDetailsViewModel With {
            .Invoice = invoice,
            .Company = Await _invoiceService.GetCompanyDetailsAsync(),
            .LineItems = Await _invoiceService.GetLineItemsAsync(invoiceId),
            .TaxDetails = Await _invoiceService.GetTaxDetailsAsync(invoiceId)
        }

        ' Render to HTML string
        Dim html As String = Me.RenderPartialViewToString("~/Views/Invoice/DetailsPdf.cshtml", viewModel)

        ' Add custom styling for PDF
        html = $"
            <html>
            <head>
                <style>
                    body {{ font-family: Arial, sans-serif; }}
                    .invoice-header {{ background-color: #f0f0f0; padding: 20px; }}
                    .line-items {{ width: 100%; border-collapse: collapse; }}
                    .line-items th, .line-items td {{ border: 1px solid #ddd; padding: 8px; }}
                </style>
            </head>
            <body>
                {html}
            </body>
            </html>"

        ' Convert to PDF with options
        Dim renderer As New ChromePdfRenderer With {
            .RenderingOptions = New ChromePdfRenderOptions With {
                .MarginTop = 20,
                .MarginBottom = 20,
                .MarginLeft = 10,
                .MarginRight = 10,
                .PrintHtmlBackgrounds = True
            }
        }

        Dim pdf = renderer.RenderHtmlAsPdf(html)

        ' Add metadata
        pdf.MetaData.Author = "Invoice System"
        pdf.MetaData.Title = $"Invoice #{invoice.Number}"
        pdf.MetaData.CreationDate = DateTime.Now

        Return File(pdf.BinaryData, "application/pdf", $"Invoice-{invoice.Number}.pdf")
    End Function
End Class
$vbLabelText   $csharpLabel

Avant de mettre en œuvre toute solution d'authentification, assurez-vous d'avoir correctement installé IronPDF et configuré vos clés de licence.

Prêt à voir ce que vous pouvez faire d'autre? Visitez notre page de tutoriels : Convertir les PDF.

Questions Fréquemment Posées

Comment puis-je convertir du HTML en PDF lorsque le contenu se trouve derrière un formulaire de connexion ?

IronPDF propose plusieurs approches pour convertir du HTML en PDF derrière une authentification de connexion. Vous pouvez utiliser l'API ChromeHttpLoginCredentials pour l'authentification réseau TLS, ou télécharger le contenu HTML à l'aide de System.Net.WebClient ou HttpClient avec les en-têtes d'authentification appropriés avant de le convertir en PDF avec IronPDF.

Qu'est-ce que ChromeHttpLoginCredentials et comment l'utiliser ?

ChromeHttpLoginCredentials est l'API d'IronPDF pour gérer l'authentification réseau. Vous pouvez l'utiliser en définissant la propriété LoginCredentials sur ChromePdfRenderer avec votre nom d'utilisateur et votre mot de passe, ce qui permet à IronPDF de s'authentifier automatiquement lors du rendu en PDF d'URL protégées par un mot de passe.

Puis-je gérer des connexions basées sur des formulaires HTML pour la conversion PDF ?

Oui, IronPDF prend en charge les connexions basées sur des formulaires HTML. L'approche recommandée consiste à utiliser System.Net.WebClient ou HttpClient pour gérer le processus de connexion, télécharger le contenu HTML authentifié, puis utiliser la méthode IronPDF's RenderHtmlAsPdf pour convertir le HTML téléchargé en PDF.

Comment puis-je télécharger des ressources HTML telles que des images et des feuilles de style à partir de pages authentifiées ?

Vous pouvez utiliser HtmlAgilityPack pour analyser le code HTML téléchargé et extraire les URL de ressources telles que les images et les feuilles de style. Utilisez ensuite System.Net.WebClient pour télécharger chaque ressource avec les mêmes en-têtes d'authentification avant de convertir le paquet HTML complet en PDF avec IronPDF.

Quelle est la meilleure pratique pour gérer les jetons ou en-têtes d'authentification ?

Lorsque vous utilisez IronPDF avec des jetons d'authentification, téléchargez le HTML en utilisant HttpClient ou WebClient avec vos en-têtes d'authentification (tels que les jetons Bearer). Une fois que vous avez le contenu HTML authentifié en mémoire ou sauvegardé sur le disque, utilisez IronPDF's ChromePdfRenderer pour le convertir en PDF.

Existe-t-il une solution de contournement pour l'authentification de connexion MVC ?

Oui, IronPDF fournit des solutions de contournement pour les scénarios d'authentification de connexion MVC. L'approche recommandée consiste d'abord à s'authentifier et à télécharger le contenu HTML à l'aide de clients HTTP .NET standard, puis à transmettre le HTML authentifié directement au moteur de rendu d'IronPDF plutôt que de demander à IronPDF de gérer l'authentification.

Curtis Chau
Rédacteur technique

Curtis Chau détient un baccalauréat en informatique (Université de Carleton) et se spécialise dans le développement front-end avec expertise en Node.js, TypeScript, JavaScript et React. Passionné par la création d'interfaces utilisateur intuitives et esthétiquement plaisantes, Curtis aime travailler avec des frameworks modernes ...

Lire la suite
Prêt à commencer?
Nuget Téléchargements 18,560,885 | Version : 2026.4 vient de sortir
Still Scrolling Icon

Vous faites encore défiler ?

Vous voulez une preuve rapidement ? PM > Install-Package IronPdf
exécuter un échantillon Regardez votre code HTML se transformer en PDF.