gpt4 book ai didi

razor - 在 dotnet core 2 中生成 Razor HTML 电子邮件

转载 作者:行者123 更新时间:2023-12-03 13:21:46 24 4
gpt4 key购买 nike

如何使用 dotnetcore 中的 Razor 生成电子邮件 (html),而不是从 MVC 应用程序(从控制台应用程序思考)?

RazorEngine 在 .net 4.x 中表现出色,但在 dotnet 核心中无法正常工作。

RazorEngineLight 在 dotnet core 1.x 中工作,但在 2.x 中不工作。

这篇文章中提到了一些其他选项:Using Razor outside of MVC in .NET Core但它们实际上都不能在 .net core 2.0 中工作

两年后编辑:

万一有人来这里寻找答案...我 (OP) 已经不再完全依赖 Razor 使用模板等生成电子邮件。它非常脆弱且容易出错 - 令人头疼不已。这些天我更喜欢 Mandrill 或 Sendgrid - 使用模板。

最佳答案

在对 this provided answer from the link provided 的评论中你说

I am not able to get this to work. I get the error: Unable to resolve service for type 'Microsoft.AspNetCore.Mvc.Razor.IRazorViewEngine' while attempting to activate 'Mvc.RenderViewToString.RazorViewToStringRenderer'.'

这通常表示所需服务未在服务集合中注册,因此提供者无法在需要时解析该服务。

那个答案没有提到额外的服务配置,只有

public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IViewRender, ViewRender>();
}

因为它已经在 Asp.Net Core 环境中运行,这意味着在控制台应用程序中手动添加的服务已经在启动时完成。

注意来自 the answer 的这个片段链接到您评论的答案。

private static void ConfigureDefaultServices(IServiceCollection services) {
var applicationEnvironment = PlatformServices.Default.Application;
services.AddSingleton(applicationEnvironment);

var appDirectory = Directory.GetCurrentDirectory();

var environment = new HostingEnvironment
{
WebRootFileProvider = new PhysicalFileProvider(appDirectory),
ApplicationName = "RenderRazorToString"
};
services.AddSingleton<IHostingEnvironment>(environment);

services.Configure<RazorViewEngineOptions>(options =>
{
options.FileProviders.Clear();
options.FileProviders.Add(new PhysicalFileProvider(appDirectory));
});

services.AddSingleton<ObjectPoolProvider, DefaultObjectPoolProvider>();

var diagnosticSource = new DiagnosticListener("Microsoft.AspNetCore");
services.AddSingleton<DiagnosticSource>(diagnosticSource);

services.AddLogging();
services.AddMvc();
services.AddSingleton<RazorViewToStringRenderer>();
}

上面重要的部分是

services.AddMvc();

这会将相关的 View 引擎依赖添加到服务集合中

MvcServiceCollectionExtensions.cs

public static IMvcBuilder AddMvc(this IServiceCollection services) {

//...code removed for brevity

// Default framework order
builder.AddFormatterMappings();
builder.AddViews();
builder.AddRazorViewEngine();
builder.AddRazorPages();
builder.AddCacheTagHelper();

//...code removed for brevity

}

当前呈现的所有其他内容都是合理的,并且应该按预期工作。

你应该回顾一下

https://github.com/aspnet/Entropy/tree/93ee2cf54eb700c4bf8ad3251f627c8f1a07fb17/samples/Mvc.RenderViewToString

并遵循类似的结构来让代码在您的场景中工作。从那里您可以开始进行自定义修改并监控它在哪里中断。

.Net Core 的模块化特性允许进行此类自定义,因为可以剥离不同的模块并在其他环境中使用。

关于razor - 在 dotnet core 2 中生成 Razor HTML 电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50294999/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com