Asp.NET Core,发布后找不到cshtml的视图

问题描述

我在我的Asp.NET CORE服务中使用RazorEngine,该服务会生成动态html页面,该页面将通过EMAIL从View文件夹中存储的cshtml文件通过EMAIL发送。

问题在于,发布网站后,该服务无法找到Views/Emails/EmailRiepilogo.cshtml的路径,因为发布时甚至没有创建View文件夹...

那么发布服务时如何引用EmailRiepilogo.cshtml路径?

这是我读取文件的方式:

string template = File.ReadAllText("Views/Emails/EmailRiepilogo.cshtml");

这是错误

找不到路径'E:\VS2019\Project\bin\Debug\netcoreapp3.1\publish\Views\Emails\EmailRiepilogo.cshtml'.

的一部分

我应该将静态文件创建为cshtml吗?

解决方法

您不知道将在何处(就主机服务器中的文件夹结构而言)托管应用程序。同时,诸如File.ReadAllText之类的方法最适合绝对路径。您需要将相对路径“ Views / Emails / EmailRiepilogo.cshtml”转换为绝对路径。一种方法是在Asp.Net Core中使用IHostingEnvironment(在Asp.Net中使用Server.MapPath)。只需将其注入您的服务/控制器并

string filename = Path.Combine(_hostingEnv.ContentRootPath,"Views/Emails/EmailRiepilogo.cshtml");
string template = File.ReadAllText(filename);

当然,发布项目后,您需要检查文件是否存在。

,

通过将每个cshtml文件的Compile Action设置为Integrated Resource并将复制到输出目录到Copy always来解决此问题,通过这种方式,将生成包含cshtml文件的View文件夹并读取文件正确。