将Razor View渲染为ASP.NET Core中的字符串
我使用RazorEngine解析MVC 6项目中的模板,如下所示:
Engine.Razor.RunCompile(File.ReadAllText(fullTemplateFilePath), templateName, null, model);
对于beta 6来说,它可以正常工作。在升级到beta 7并出现以下错误后,它无法工作:
MissingMethodException:找不到方法:“无效Microsoft.AspNet.Razor.CodeGenerators.GeneratedClassContext.set_ResolveUrlMethodName(System.String)”。在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,此代码段可能会帮助您:
- 创建一个单独的服务,因此,如果您不在控制器环境中(例如,从命令行或在队列运行器上),则可以使用它…
- 在
Startup
课程的 IoC容器中注册此服务
https://gist.github.com/ahmad-
moussawi/1643d703c11699a6a4046e57247b4d09
用法
// using a Modelstring 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)
以上是 将Razor View渲染为ASP.NET Core中的字符串 的全部内容, 来源链接: utcz.com/qa/425450.html