asp.net核心 – 渲染Razor视图到ASP.NET核心的字符串

前端之家收集整理的这篇文章主要介绍了asp.net核心 – 渲染Razor视图到ASP.NET核心的字符串前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我使用 RazorEngine来解析我的MVC 6项目中的模板,如下所示:
Engine.Razor.RunCompile(File.ReadAllText(fullTemplateFilePath),templateName,null,model);

它适用于beta 6.它在升级到beta 7后出现错误

MissingMethodException: Method not found: “Void Microsoft.AspNet.Razor.CodeGenerators.GeneratedClassContext.set_ResolveUrlMethodName(System.String)”.
in RazorEngine.Compilation.CompilerServiceBase.CreateHost(Type templateType,Type modelType,String className)

这是global.json:

{
  "projects": [ "src","test" ],"sdk": {
    "version": "1.0.0-beta7","runtime": "clr","architecture": "x64"
  }
}

这是project.json:

...
"dependencies": {
    "EntityFramework.sqlServer": "7.0.0-beta7","EntityFramework.Commands": "7.0.0-beta7","Microsoft.AspNet.Mvc": "6.0.0-beta7","Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-beta7","Microsoft.AspNet.Authentication.Cookies": "1.0.0-beta7","Microsoft.AspNet.Authentication.Facebook": "1.0.0-beta7","Microsoft.AspNet.Authentication.Google": "1.0.0-beta7","Microsoft.AspNet.Authentication.MicrosoftAccount": "1.0.0-beta7","Microsoft.AspNet.Authentication.Twitter": "1.0.0-beta7","Microsoft.AspNet.Diagnostics": "1.0.0-beta7","Microsoft.AspNet.Diagnostics.Entity": "7.0.0-beta7","Microsoft.AspNet.Identity.EntityFramework": "3.0.0-beta7","Microsoft.AspNet.Server.IIS": "1.0.0-beta7","Microsoft.AspNet.Server.WebListener": "1.0.0-beta7","Microsoft.AspNet.StaticFiles": "1.0.0-beta7","Microsoft.AspNet.Tooling.Razor": "1.0.0-beta7","Microsoft.Framework.Configuration.Abstractions": "1.0.0-beta7","Microsoft.Framework.Configuration.Json": "1.0.0-beta7","Microsoft.Framework.Configuration.UserSecrets": "1.0.0-beta7","Microsoft.Framework.Logging": "1.0.0-beta7","Microsoft.Framework.Logging.Console": "1.0.0-beta7","Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0-beta7","RazorEngine": "4.2.2-beta1"
  },...
  "frameworks": {
    "dnx451": { }
  },...

我的模板是:

@model dynamic
@{
	Layout = null;
}

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
	<Meta charset="utf-8" />
	<title>Registration</title>
</head>
<body>
<p>
    Hello,@Model
</p>
</body>
</html>

有人有类似的问题吗?
还有另一种方法来解析MVC 6中的模板?

解决方法

2016年7月更新

在以下版本1.0.0,RC2上工作正常

谁的目标是aspnetcore RC2,此代码段可能会帮助您:

>创建一个单独的服务,所以你可以使用它,如果你不在控制器上下文,例如从命令行或队列转轮等…
>在启动类中的IoC容器中注册此服务

https://gist.github.com/ahmad-moussawi/1643d703c11699a6a4046e57247b4d09

用法

// using a Model
string html = view.Render("Emails/Test",new Product("Apple"));

// using a Dictionary<string,object>
var viewData = new Dictionary<string,object>();
viewData["Name"] = "123456";

string html = view.Render("Emails/Test",viewData);

笔记

Razor中的链接被渲染为相对URL,因此这对于外部视图(如电子邮件等)不起作用.

至于现在,我正在生成控制器上的链接,并通过viewmodel将其传递给视图.

信用

来源是从(感谢@pholly)提取https://github.com/aspnet/Entropy/blob/dev/samples/Mvc.RenderViewToString/RazorViewToStringRenderer.cs)

猜你在找的asp.Net相关文章