c# - 如何设置 C# 元素以将 css 从本地 .css 文件内联到 HTML 中? PreMailer.Net 可以做到这一点吗?

标签 c# html css asp.net premailer

我正在尝试更新电子邮件模板系统以允许使用外部 .css 文件,而不必内联编写所有样式。我的元素在 ASP.NET 中,据我所知,最常用且功能最丰富的内联器是 PreMailer.Net ,尽管如果有更适合我需要的软件包,我愿意使用其他软件包。这是我正在尝试做的事情的简要说明:

文件系统

G:/templates/
  index.html
  style.css

内联.cs

string htmlSource = File.ReadAllText("G:\\templates\\index.html");
var uri = new Uri("G:\\templates\\");
var result = PreMailer.MoveCssInline(uri, htmlSource);

index.html

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" type="text/css" href='style.css'>
    </head>
    <body>
    </body>
</html>

当我运行此代码时 - 我收到以下错误:

Unable to cast object of type 'System.Net.FileWebResponse' to type 'System.Net.HttpWebResponse'.

根据文档,我不清楚 PreMailer.Net 是否支持此用例。它声称如果您指定 BaseUri 参数,则可以使用相对 URL。运行 PreMailer.Net 的 C# 代码具有必要的上下文和对该文件路径的访问权限,事实证明它可以将 HTML 文件读入字符串。

最佳答案

此问题似乎已在刚刚发布的 2.1.1 中得到修复根据 this GitHub 问题:

Add support on fetching Uri with local filepath like "file:///C:/website/style.css"

It's required when we optimize the performance by fetching the local resource internally instead of making external web request towards internal resource. e.g. As I know the css is actually inside the local storage, it make sense to just make a fast local fetch ("file:///C:/website/style.css") instead of external web request ("https://www.example.com/style.css")

So I can now initialize a PreMailer instance with BaseUri "file:///" + new Uri(System.Web.Hosting.HostingEnvironment.MapPath("~/"), UriKind.Absolute)

It's how I boost the performance for my client, just share my code here.

关于c# - 如何设置 C# 元素以将 css 从本地 .css 文件内联到 HTML 中? PreMailer.Net 可以做到这一点吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57965176/

相关文章:

javascript - 当这些样式移入 .CSS 文件时,直接应用于元素的样式将丢失

javascript - 如果背景图像 url = 那么

c# - 委托(delegate)给 C# 中的属性

c# - 在 unity3d 中更改 Material Assets

c# - 如何在 HtmlAgilityPack 中替换/添加根元素?

html - 摆脱页脚右下角的空白

c# - 如何在多个不相关的解决方案中使用(和编辑)一个项目?

c# - 从子文件夹解析程序集的正确方法

javascript - 无法在 d3 应用程序中的文本标记上添加 Bootstrap Popover

html - 为什么导航栏按钮不居中?