Asp.net核心2.1.0 RazorTemplateEngine不能正常工作

时间:2018-05-24 14:58:06

标签: asp.net-core compile-time

我在asp.net核心上的编译时在razortemplate引擎上进行html minify,但更新项目asp.net核心2.1.0后razortemplate引擎无效。

它不会调用CreateCodeDocument方法。 示例代码如下。

public class CustomRazorTemplateEngine : RazorTemplateEngine
{
    private HtmlMinifier _htmlMinifier = new HtmlMinifier();

    public CustomRazorTemplateEngine(RazorEngine engine, RazorProject project) : base(engine, project)
    {
        Options.ImportsFileName = "_ViewImports.cshtml";
    }

    public override RazorCodeDocument CreateCodeDocument(RazorProjectItem projectItem)
    {
        using (var inputStream = projectItem.Read())
        {
            using (var reader = new StreamReader(inputStream))
            {
                var text = reader.ReadToEnd();

                var markupStart = text.IndexOf("<!DOCTYPE");
                var directives = text.Substring(0, markupStart);
                var markup = text.Substring(markupStart);
                text = directives + Minify(markup);
                var byteArray = Encoding.UTF8.GetBytes(text);
                var minifiedInputStream = new MemoryStream(byteArray);

                var source = RazorSourceDocument.ReadFrom(minifiedInputStream, projectItem.PhysicalPath);
                var imports = GetImports(projectItem);

                return RazorCodeDocument.Create(source, imports);
            }
        }
    }

    private string Minify(string markup)
    {
        MarkupMinificationResult result = _htmlMinifier.Minify(markup, string.Empty, Encoding.UTF8, true);

        if (result.Errors.Count == 0)
        {
            MinificationStatistics statistics = result.Statistics;
            if (statistics != null)
            {
                Console.WriteLine();
                Console.WriteLine($"Original size: {statistics.OriginalSize:N0} Bytes | Minified size: {statistics.MinifiedSize:N0} Bytes | Saved: {statistics.SavedInPercent:N2}%");
            }
            //Console.WriteLine($"{Environment.NewLine}Minified content:{Environment.NewLine}{Environment.NewLine}{result.MinifiedContent}");

            return result.MinifiedContent;
        }
        else
        {
            IList<MinificationErrorInfo> errors = result.Errors;

            Console.WriteLine();
            Console.WriteLine($"Found {errors.Count:N0} error(s):");

            foreach (var error in errors)
            {
                Console.WriteLine($" - Line {error.LineNumber}, Column {error.ColumnNumber}: {error.Message}");
            }

            return markup;
        }
    }
}

}

startup.cs    services.AddSingleton();

0 个答案:

没有答案