如何在 IronPDF 中使用 Cookie
在网络技术的背景下,Cookies是网站在用户的计算机或设备上存储的小数据片段。它们具有各种用途,从会话管理开始,帮助保持用户登录状态,到跟踪和分析,收集用户行为数据以改进网站。 然而,使用cookies已经引发了对隐私的讨论,导致了像GDPR和CCPA这样的法规的出台,现代网络浏览器提供了对cookie管理的用户控制来解决这些问题。
开始使用IronPDF
立即在您的项目中开始使用IronPDF,并享受免费试用。
如何在 IronPDF 中使用 Cookie
- 从 NuGet 下载 IronPDF
- 准备使用自定义 cookie 呈现 HTML 内容
- 配置RequestContext属性以启用 Cookie 的使用
- 使用
ApplyCookies
方法来应用Cookies - 使用 CustomCookies 属性来实现自定义 cookies
应用 Cookies 示例
在使用方法应用cookies之前,将RequestContext属性设置为RequestContexts.Global。 然后,创建 ChromeHttpLoginCredentials 类并将其传递给 ApplyCookies
方法。 渲染器现在已经可以用于将带有 cookies 的 HTML 内容渲染为 PDF。
:path=/static-assets/pdf/content-code-examples/how-to/cookies-apply-cookies.cs
using IronPdf;
// Instantiate ChromePdfRenderer
ChromePdfRenderer renderer = new ChromePdfRenderer();
renderer.RenderingOptions.RequestContext = IronPdf.Rendering.RequestContexts.Global;
ChromeHttpLoginCredentials credentials = new ChromeHttpLoginCredentials() {
NetworkUsername = "testUser",
NetworkPassword = "testPassword"
};
string uri = "http://localhost:51169/Invoice";
// Apply cookies
renderer.ApplyCookies(uri, credentials);
RequestContexts 枚举:此枚举定义了用于建立各个渲染之间关系的浏览器请求上下文。 管理 cookie 和用户偏好设置是必不可少的。
- 隔离:创建一个与之前或未来的渲染隔离的新请求上下文。 建议确保当前渲染不受之前渲染的影响。
- 全局:使用全局请求上下文,该上下文在所有渲染之间共享。 在某些情况下,对于在渲染之间保持特定浏览器状态很有用。
- 自动:默认为IronPdf.Rendering.RequestContexts.Isolated,但如果用户曾调用过IronPdf.ChromePdfRenderer.ApplyCookies(System.String, IronPdf.ChromeHttpLoginCredentials)则切换到IronPdf.Rendering.RequestContexts.Global。
应用自定义Cookie示例
在请求中使用自定义 Cookie 需要设置 CustomCookies 属性。 此属性接受一个键值对字典,键和值都是字符串。
:path=/static-assets/pdf/content-code-examples/how-to/cookies-apply-custom-cookies.cs
using IronPdf;
using System;
using System.Collections.Generic;
// Instantiate ChromePdfRenderer
ChromePdfRenderer renderer = new ChromePdfRenderer();
Dictionary<string, string> customCookies = new Dictionary<string, string>();
// Apply custom cookies
renderer.RenderingOptions.CustomCookies = customCookies;
var uri = new Uri("https://localhost:44362/invoice");
PdfDocument pdf = renderer.RenderUrlAsPdf(uri);