简体   繁体   English

Asp.NET 内核,发布时找不到cshtml的视图

[英]Asp.NET Core, unable to find View of cshtml when published

I'm using RazorEngine in my Asp.NET CORE service which generate dynamic html pages to be sent via EMAIL from a cshtml file that is stored in View folder..我在我的 Asp.NET CORE 服务中使用RazorEngine ,它生成动态 html 页面,这些页面将通过 EMAIL 从存储在 View 文件夹中的 cshtml 文件发送。

The issue is that when the website is published the service is unable to find path to Views/Emails/EmailRiepilogo.cshtml as on publish the View folder is not even created...问题是,当网站发布时,服务无法找到Views/Emails/EmailRiepilogo.cshtml的路径,因为发布时甚至没有创建 View 文件夹......

So how can I reference to EmailRiepilogo.cshtml path when the service is published?那么如何在服务发布时引用EmailRiepilogo.cshtml 路径呢?

Here is how I'm reading the file:这是我读取文件的方式:

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

And here is the error:这是错误:

Could not find a part of the path 'E:\VS2019\Project\bin\Debug\netcoreapp3.1\publish\Views\Emails\EmailRiepilogo.cshtml'.找不到路径'E:\VS2019\Project\bin\Debug\netcoreapp3.1\publish\Views\Emails\EmailRiepilogo.cshtml'.

Should I just create static file as cshtml?我应该将 static 文件创建为 cshtml 吗?

You don't know where (in terms of folder structure in the host server) your application will be hosted.您不知道您的应用程序将托管在何处(就主机服务器中的文件夹结构而言)。 At the same time, methods like File.ReadAllText work best with absolute paths.同时,像File.ReadAllText这样的方法在使用绝对路径时效果最好。 You need to convert the relative path "Views/Emails/EmailRiepilogo.cshtml" to an absolute path.您需要将相对路径“Views/Emails/EmailRiepilogo.cshtml”转换为绝对路径。 One way is to use IHostingEnvironment in Asp.Net Core (or Server.MapPath in Asp.Net).一种方法是在 Asp.Net Core 中使用IHostingEnvironment (或在 Asp.Net 中使用Server.MapPath )。 Just inject it to your service/controller and只需将其注入您的服务/控制器,然后

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

Of course, you need to check if the file exists where you expect after publishing the project.当然,您需要在发布项目后检查文件是否存在于您期望的位置。

我已经解决了通过将每个 cshtml 文件编译操作设置为Integrated Resource并将复制到输出目录Copy always到这样的方式来生成带有 cshtml 文件的视图文件夹并正确读取文件。

I had excact same problem.我有完全相同的问题。 Cshtml file Build action was somehow changed from Content -> None. Cshtml 文件构建操作以某种方式从内容 -> 无更改。 It worked on local but not when published to server.它在本地工作,但在发布到服务器时不起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM