将 Html 转换为 Pdf 时出现身份验证失败错误

Authentication fail error on convert Html to Pdf

我尝试使用 "HtmlToPdf" nuget 将 Html 转换为 PDF,它在本地测试中工作正常,但是当我将站点上传到主机时出现此错误:

 Conversion error: Authentication error.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Exception: Conversion error: Authentication error.

这是我的转换方法代码

        [AllowAnonymous]
        public ActionResult Convert(int id)
        {

            HtmlToPdf converter = new HtmlToPdf();
            var context = System.Web.HttpContext.Current;
            string baseUrl = context.Request.Url.Host + ":"+context.Request.Url.Port + "/Doctor/DietTherapy/LineRegimePrint/";
            PdfDocument doc = converter.ConvertUrl(baseUrl + id);

            // save pdf document
            byte[] pdf = doc.Save();

            // close pdf document
            doc.Close();

            // return resulted pdf document
            FileResult fileResult = new FileContentResult(pdf, "application/pdf");
            fileResult.FileDownloadName = "Document.pdf";
            return fileResult;
        }

我如何授权用户进行此转换?

听起来您只需要 authenticate the request 由 PDF 库制作即可。例如,如果它使用基本 HTTP 身份验证:

HtmlToPdf converter = new HtmlToPdf();
converter.Options.Authentication.Username = "some username";
converter.Options.Authentication.Password = "some password";
// the rest of your code...

链接的文档还包含其他身份验证方法的示例。

您是否检查过是否在这行代码中获得了正确的值(当 运行 在主机服务器上时)?

string baseUrl = context.Request.Url.Host + ":"+context.Request.Url.Port + "/Doctor/DietTherapy/LineRegimePrint/";

虽然您的开发机器的 IIS Express 使用匿名身份验证,但您的托管服务器可能正在使用 Windows 身份验证或其他类型。检查 IIS 管理器以查看差异。

SelectPDF 的库以某种方式创建了一个单独的进程来执行 HtmlToPdf 转换,该进程在 IUser 之外,因此,服务器要求进行身份验证。

对于 Windows 身份验证设置,您可以为此目的使用通用用户登录帐户并填充上述线程中提到的所需属性,一切都会很好。

converter.Options.Authentication.Username = "WindowsUser";
converter.Options.Authentication.Password = "WindowsPassword";