在视图中呈现包含剃刀代码的字符串

Dav*_*vid 3 .net c# asp.net asp.net-mvc razor

在这里考虑 CMS 用例。想象一个这样的视图:

// /Home/Index.cshtml
@model object
@{
  var str = "My <b>CMS</b> content with razor code: @Html.ActionLink(\"Click\", \"Home\")"
}
@Html.MyCustomRazorStringRenderer(Model)
Run Code Online (Sandbox Code Playgroud)

预期输出:

My <b>CMS</b> content with razor code: <a href="/Home/Click">Click</a>
Run Code Online (Sandbox Code Playgroud)

MyCustomRazorStringRenderer 是什么样的?它必须以某种方式做某事。就像创建/使用 ViewContext 并渲染它(就像这里:将视图渲染为字符串)但我无法完全理解它。

And*_*lad 5

您必须创建一个包含扩展方法的静态类。该方法必须返回一个包含安全呈现的 HTML 输出的MvcHtmlString实例。话虽如此,renderedOutput正确使用意味着“劫持”Razor 渲染器,这很棘手。

您真正要做的是在其预期环境之外使用 Razor 引擎,如下所述:http : //vibrantcode.com/blog/2010/7/22/using-the-razor-parser-outside-of- aspnet.html

这里也有很多不错的资料,从中得到了很多启发,下面的代码:http : //www.codemag.com/article/1103081

这些类是此操作的起点:RazorEngineHostRazorTemplateEngineCSharpCodeProviderHtmlHelper

工作代码

我实际上得到了一个几乎可以工作的版本,但意识到这是一件非常徒劳的事情。Razor 引擎通过生成代码工作,然后必须使用CSharpCodeProvider. 这需要时间。很多时间!

唯一可行且有效的方法是将模板字符串保存在某处,预编译它们,并在调用时调用这些已编译的模板。这使得它对于您所追求的内容基本上毫无用处,因为这正是带有 Razor 的 ASP.NET MVC 所擅长的 - 将视图保持在一个好的位置,预编译它们,并在引用时调用它们。更新:嗯,也许大量的缓存可能会有所帮助,但我实际上仍然不会推荐这个解决方案。

生成代码时,Razor 会发出对this.Write和 的调用this.WriteLiteral。因为this是从您自己编写的基类继承的对象,所以由您提供Write和 的实现WriteLiteral

如果您HtmlHelper在模板字符串中使用任何其他扩展,则需要为所有这些扩展包含程序集引用和命名空间导入。下面的代码添加了最常见的。由于匿名类型的性质,这些不能用于模型类。

MyRazorExtensions 类

public static class MyRazorExtensions
{
    public static MvcHtmlString RazorEncode(this HtmlHelper helper, string template)
    {
        return RazorEncode(helper, template, (object)null);
    }

    public static MvcHtmlString RazorEncode<TModel>(this HtmlHelper helper, string template, TModel model)
    {
        string output = Render(helper, template, model);
        return new MvcHtmlString(output);
    }

    private static string Render<TModel>(HtmlHelper helper, string template, TModel model)
    {
        // 1. Create a host for the razor engine
        //    TModel CANNOT be an anonymous class!
        var host = new RazorEngineHost(RazorCodeLanguage.GetLanguageByExtension("cshtml");
        host.DefaultNamespace = typeof(MyTemplateBase<TModel>).Namespace;
        host.DefaultBaseClass = nameof(MyTemplateBase<TModel>) + "<" + typeof(TModel).FullName + ">";
        host.NamespaceImports.Add("System.Web.Mvc.Html");

        // 2. Create an instance of the razor engine
        var engine = new RazorTemplateEngine(host);

        // 3. Parse the template into a CodeCompileUnit
        using (var reader = new StringReader(template))
        {
            razorResult = engine.GenerateCode(reader);
        }
        if (razorResult.ParserErrors.Count > 0)
        {
            throw new InvalidOperationException($"{razorResult.ParserErrors.Count} errors when parsing template string!");
        }

        // 4. Compile the produced code into an assembly
        var codeProvider = new CSharpCodeProvider();
        var compilerParameters = new CompilerParameters { GenerateInMemory = true };
        compilerParameters.ReferencedAssemblies.Add(typeof(MyTemplateBase<TModel>).Assembly.Location);
        compilerParameters.ReferencedAssemblies.Add(typeof(TModel).Assembly.Location);
        compilerParameters.ReferencedAssemblies.Add(typeof(HtmlHelper).Assembly.Location);
        var compilerResult = codeProvider.CompileAssemblyFromDom(compilerParameters, razorResult.GeneratedCode);
        if (compilerResult.Errors.HasErrors)
        {
            throw new InvalidOperationException($"{compilerResult.Errors.Count} errors when compiling template string!");
        }

        // 5. Create an instance of the compiled class and run it
        var templateType = compilerResult.CompiledAssembly.GetType($"{host.DefaultNamespace}.{host.DefaultClassName}");
        var templateImplementation = Activator.CreateInstance(templateType) as MyTemplateBase<TModel>;
        templateImplementation.Model = model;
        templateImplementation.Html = helper;
        templateImplementation.Execute();

        // 6. Return the html output
        return templateImplementation.Output.ToString();
    }
}
Run Code Online (Sandbox Code Playgroud)

MyTemplateBase<> 类

public abstract class MyTemplateBase<TModel>
{
    public TModel Model { get; set; }
    public HtmlHelper Html { get; set; }

    public void WriteLiteral(object output)
    {
        Output.Append(output.ToString());
    }

    public void Write(object output)
    {
        Output.Append(Html.Encode(output.ToString()));
    }

    public void Write(MvcHtmlString output)
    {
        Output.Append(output.ToString());
    }

    public abstract void Execute();

    public StringBuilder Output { get; private set; } = new StringBuilder();
}
Run Code Online (Sandbox Code Playgroud)

测试.cshtml

@using WebApplication1.Models

<h2>Test</h2>

@Html.RazorEncode("<p>Paragraph output</p>")
@Html.RazorEncode("<p>Using a @Model</p>", "string model" )
@Html.RazorEncode("@for (int i = 0; i < 100; ++i) { <p>@i</p> }")
@Html.RazorEncode("@Html.ActionLink(Model.Text, Model.Action)", new TestModel { Text = "Foo", Action = "Bar" })
Run Code Online (Sandbox Code Playgroud)

更新

做这个“实时” - 如果你不重视缓存,让 Razor 为每个页面加载编译和运行显然太慢了,但是如果你打破我的代码片段并让你的 CMS 在内容出现时自动请求重新编译页面更改时,您可以在这里做一些非常有趣的事情。