简体   繁体   English

在控制台应用程序中使用 Razor 的最佳方式是什么

[英]What is the best way to use Razor in a console application

I know similar questions have been asked before, but the only answers are six years old, and the projects people refer to seem like they're not being maintained.我知道以前有人问过类似的问题,但唯一的答案是六年前的,人们提到的项目似乎没有得到维护。

I want to use Razor in a console app or a class library to render HTML.我想在控制台应用程序或类库中使用 Razor 来呈现 HTML。 I would also like to have working Intellisense in the .cshtml files.我还想在 .cshtml 文件中使用 Intellisense。

Currently, I am able to jury-rig this by doing the following:目前,我可以通过执行以下操作来对此进行评判:

  • Create console app.创建控制台应用程序。
  • Add .cshtml file.添加 .cshtml 文件。
  • In Properties, set the Custom Tool property to RazorTemplatePreprocessor在属性中,将Custom Tool属性设置为RazorTemplatePreprocessor

This causes Razor syntax to be recognized.这会导致 Razor 语法被识别。 So if you have Test.cshtml , it generates a class called Test that you can use like so:因此,如果您有Test.cshtml ,它会生成一个名为Test的类,您可以像这样使用它:

var test = new Test();
test.Model = "Hi there";
var html = test.GenerateString();

Console.WriteLine(html);

This is just about good enough for my purposes.这对于我的目的来说已经足够了。 However, the actual coding experience within the .cshtml file is pretty broken:但是,.cshtml 文件中的实际编码体验非常糟糕:

  • There are red squigglies all over the place complaining about:到处都是红色的波浪线抱怨:
  • Not being able to use var because it's C# 2.不能使用var因为它是 C# 2。
  • Saying the type or namespace of various types can't be found.说各种类型的类型或命名空间都找不到。
  • The above is especially true of types imported from other libraries.从其他库导入的类型尤其如此。
  • The @model keyword is not recognized.无法识别@model关键字。
  • Intellisense sometimes works, sometimes doesn't.智能感知有时有效,有时无效。

Weirdly, if you just ignore all of these errors, the HTML is actually generated correctly, including use of the libraries and @model keyword that the Razor engine complained about.奇怪的是,如果您忽略所有这些错误,实际上会正确生成 HTML,包括使用 Razor 引擎抱怨的库和 @model 关键字。 However, this causes major mental clutter because if you have any number of .cshtml files, you very quickly get into hundreds and thousands of these errors mixed in with real errors.然而,这会导致严重的心理混乱,因为如果您有任意数量的 .cshtml 文件,您很快就会陷入成百上千的这些错误与真实错误混合在一起。

Is there anything I can do to cause the actual Razor coding experience to work more like it does in an ASP.NET web app?我能做些什么来使实际的 Razor 编码体验更像在 ASP.NET Web 应用程序中那样工作?

I have been working on this sporadically since I asked the question nearly two years ago, and I believe I have a 99% non-clunky solution.自从我两年前问这个问题以来,我一直在零星地研究这个问题,我相信我有一个 99% 不笨拙的解决方案。 Everything below works for me in Visual Studio 16.4.5 .下面的所有内容在Visual Studio 16.4.5 中都适用于我。

Here's what I have learned about getting Razor to work in console and library projects.以下是我了解到的有关让 Razor 在控制台和库项目中工作的知识。

  1. Everything seems to work with the least trouble if create and consume your Razor files in a .NET Core console app.如果在 .NET Core 控制台应用程序中创建和使用您的 Razor 文件,一切似乎都能以最少的麻烦工作。
  2. You can also put your Razor files in a .NET Standard library and consume them from a .NET Core console app, though in this case there is some minor ugliness in Solution Explorer.您还可以将 Razor 文件放在 .NET Standard 库中,并从 .NET Core 控制台应用程序使用它们,但在这种情况下,解决方案资源管理器中存在一些小问题。 I don't think it has any effect on functionality, however.但是,我认为它对功能没有任何影响。
  3. Either way, both the @model and the @using keywords work correctly, Intellisense works correctly, lambda expressions work correctly, everything seems to work properly.无论哪种方式, @model@using关键字都正常工作,Intellisense 正常工作,lambda 表达式正常工作,一切似乎都正常工作。

Here's what you have to do:这是你必须做的:

To add a Razor file:添加 Razor 文件:

Add a new HTML file, but name the file with a .cshtml extension.添加一个新的 HTML 文件,但使用.cshtml扩展名命名该文件。

Select the file in Solution Explorer.在解决方案资源管理器中选择文件。 In the Properties window, under Custom Tool, enter RazorTemplatePreprocessor .在“属性”窗口中的“自定义工具”下,输入RazorTemplatePreprocessor A .cs file will immediately be generated.将立即生成.cs文件。

To consume the generated class:要使用生成的类:

var razor = new MyRazorClass();
razor.Model = "Hello from Razor";       // Assumes @model string in the Razor file; custom classes are fine too.
var html = razor.GenerateString();
Console.WriteLine(html);

To resolve the errors in the Error List (which incidentally do not seem to affect functionality but certainly create mental clutter):要解决错误列表中的错误(顺便说一句,这似乎不会影响功能,但肯定会造成精神混乱):

Add NuGet references to:将 NuGet 引用添加到:

Microsoft.AspNetCore.Mvc.Core
Microsoft.AspNetCore.Mvc.Razor

If you are adding your Razor files to a .NET Standard library, you'll get a bunch of the following errors:如果您将 Razor 文件添加到 .NET Standard 库,您将收到一系列以下错误:

Feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.

To fix this, add the following two lines to the project file:要解决此问题,请将以下两行添加到项目文件中:

<PropertyGroup>
  <TargetFramework>netstandard2.0</TargetFramework>
  <Nullable>enable</Nullable>                         <!-- Add this line -->
  <LangVersion>8.0</LangVersion>                      <!-- Add this line -->
</PropertyGroup>

At this point, the project should compile with no errors or warnings!此时,项目应该编译没有错误或警告!

However, it doesn't work perfectly.但是,它不能完美地工作。 There some oddities, which give me some concern that things might unexpectedly break on me in the future.有一些奇怪的事情,这让我担心将来事情可能会出乎意料地破坏我。

These problems only seem to occur when using Razor files from .NET Standard libraries:这些问题似乎只在使用 .NET Standard 库中的 Razor 文件时出现:

  1. The Solution Explorer sometimes shows the descendants of the .cshtml file in two different ways:解决方案资源管理器有时会以两种不同的方式显示.cshtml文件的后代:

a.一种。 In what I believe is the correct way, the .cshtml file has as its only descendant a generated .cs file.在我认为正确的方式中, .cshtml文件的唯一后代是生成的.cs文件。 That file in turn has two generated classes, YourRazorClass and YourRazorClassBase .该文件又具有两个生成的类, YourRazorClassYourRazorClassBase Each of those can be expanded to show the class members, which have nice, human-readable names.每一个都可以展开以显示类成员,它们具有很好的、人类可读的名称。

b.Sometimes, however, an underscore-prefixed class appears as a direct descendant of the .cshtml file (eg, _MyTestRazorClass ), Also, its class members are different.然而,有时下划线前缀的类显示为.cshtml文件的直接后代(例如_MyTestRazorClass ),此外,其类成员不同。

This seems to appear and disappear from the Solution Explorer and I don't think it causes any harm, but it certainly causes some mental clutter as you wonder what on earth is going on.这似乎在解决方案资源管理器中出现和消失,我认为它不会造成任何伤害,但是当您想知道到底发生了什么时,它肯定会引起一些精神混乱。

  1. In Solution Explorer, under the [Project Name] > Dependencies > Analyzers , there are a bunch of warnings that get propagated up into the same section of any project that consumes the library.在解决方案资源管理器中,在[Project Name] > Dependencies > Analyzers ,有一堆警告会传播到使用该库的任何项目的同一部分。 This also creates mental clutter.这也会造成精神混乱。 Fortunately, you can turn these off by doing the following:幸运的是,您可以通过执行以下操作来关闭这些功能:

a.一种。 Right-click the project and choose Properties .右键单击该项目并选择Properties b.Under Code Analysis , uncheck the Run on Build and Run on Live Analysis boxes.Code Analysis ,取消选中Run on BuildRun on Live Analysis框。

One final note: I have not yet tested using a .NET Standard library set up in this way inside a Xamarin project yet (this is the scenario that originally had me going down this road), but I will do so in the future and update this answer at that time.最后一个注意事项:我还没有在 Xamarin 项目中使用以这种方式设置的 .NET Standard 库进行测试(这是最初让我走这条路的场景),但我将来会这样做并更新当时的这个回答。

UPDATE: I have now used this technique in a released Xamarin app!更新:我现在已经在发布的 Xamarin 应用程序中使用了这种技术! The only weirdness is that you can't copy-paste .cshtml files to create a new one.唯一奇怪的是你不能复制粘贴 .cshtml 文件来创建一个新文件。 It screws up both the original file and the copy and you have to go edit the project file to fix things.它搞砸了原始文件和副本,你必须去编辑项目文件来解决问题。 Instead, just manually add a new file as described above each time.相反,每次只需手动添加一个新文件,如上所述。

I hope this helps someone.我希望这可以帮助别人。 And if anyone figures out what is going on with the weirdness in Solution Explorer, I would love to know!如果有人弄清楚解决方案资源管理器中的怪异是怎么回事,我很想知道!

Just use RazorEngine library.只需使用RazorEngine库。

cshtml file intellisense is supported as per documentation.根据文档支持 cshtml 文件智能感知。

I usually use T4 Templates outside ASP.NET app: https://msdn.microsoft.com/en-US/library/bb126445.aspx .我通常在 ASP.NET 应用程序之外使用 T4 模板: https : //msdn.microsoft.com/en-US/library/bb126445.aspx There are several plugins for Visual Studio which enable code highlighting, for example http://t4-editor.tangible-engineering.com/T4-Editor-Visual-T4-Editing.html . Visual Studio 有几个插件可以启用代码突出显示,例如http://t4-editor.tangible-engineering.com/T4-Editor-Visual-T4-Editing.html

Of course, T4 is not equivalent to Razor and you should learn syntax in order to use it, but I think using Razor outside webapp is bad style...当然,T4 不等同于 Razor,你应该学习语法才能使用它,但我认为在 webapp 之外使用 Razor 是不好的风格......

Using T4 you can create from templates your own classes with custom strongly typed properties and constructors, and that's much more than Razor can.使用 T4,您可以从模板创建您自己的具有自定义强类型属性和构造函数的类,这远远超过 Razor。

You can upgrade to C#4 by adding the nuget packgage:您可以通过添加 nuget 包升级到 C#4:

Microsoft.CodeDom.Providers.DotNetCompilerPlatform

This will give you the var keyword.这将为您提供var关键字。

Also, you can get intellisense for your template parameters doing the following此外,您可以通过执行以下操作获得模板参数的智能感知

  1. Create a new .cs file创建一个新的 .cs 文件
  2. Inside it, add a partial class with the same name as the one automaticaly generated by the .cshtml file.在其中添加一个与 .cshtml 文件自动生成的同名的部分类。 Something like that:类似的东西:

public partial class htmlRazor : htmlRazorBase { public DateTime myDate}

  1. Add a constructor to this partial class that will take some input parameters:向这个部分类添加一个构造函数,它将接受一些输入参数:

public htmlRazor(DateTime _mydate) {myDate = _mydate}

  1. Add the following lines at the top of your .cshtml file:在 .cshtml 文件的顶部添加以下几行:

@using yourNameSpace @*Make sure the parameter below have exactly the same name as the variable inside the partial class (public DateTime myDate). This line will be full of errors, but you can safely ignore them.*@ @{htmlRazor agrs = new htmlRazor(myDate);}

You can now access your parameters inside the razor code by doing agrs.myDate for exemple.您现在可以通过执行agrs.myDate来访问剃刀代码中的参数,例如。

As a last note, my razor project is actualy a class library (creates a .dll file).最后一点,我的 razor 项目实际上是一个类库(创建一个 .dll 文件)。 I reference this library from a second console application project.我从第二个控制台应用程序项目中引用了这个库。 I then create the html from the template like that:然后我从模板创建 html,如下所示:

htmlRazor html = new htmlRazor(DateTime.Now); string htmlTxt = html.GenerateString();

最好的方法是“RazorLight” https://github.com/toddams/RazorLight简单明了

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

相关问题 从控制台应用程序中的ASP.NET Razor模板生成HTML的当前最佳解决方案是什么? - What's the current best solution for generating HTML from ASP.NET Razor templates within a Console Application? 延迟控制台应用程序几秒钟的最佳方法是什么 - What is the best way to delay a console application for a few seconds 保持控制台应用程序在后台运行的最佳方法是什么? - What is the best way to keep a console application running in the background? 如何在控制台应用程序中使用Razor View Engine? - How to use Razor View Engine in a console application? 在Web API Razor中处理视图路由的最佳方法是什么 - What is the best way to handle the view routing in Web API Razor 在MVC Razor页面上显示只读/可编辑控件的最佳方法是什么 - What is the best way to show readonly/editable controls on MVC Razor page 在C#/ Razor中使用JavaScript的最佳(或正确)方法? - Best (or correct) way to use JavaScript with C#/Razor? 使用 using 的最佳方式是什么? - What is the best way to use using? 在Web应用程序中处理DateTime的最佳方法是什么? - What is the best way to handle DateTime in a Web Application? 确定应用程序根目录的最佳方法是什么? - What is the best way to determine application root directory?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM