04
6

关于MSBuild和NSwag的深入学习

0
归档:2024年6月分类:C#和.NET

这段时间学习一个整洁架构的开源项目,这是一名澳大利亚的软件架构师在github上面分享的项目:https://github.com/jasontaylordev/CleanArchitecture

作者的架构根底扎实,而且能灵活运用各种最新最简洁的技术知识,这个项目就用到非常多,我把代码pull下来之后发现直接编译过程中出了不少错误,花了两天时间都解决了。其中很大一部分是关于前端项目的内容,作者直接使用MSBuild来完成打包和创建,这只是我第一次看到。

另外还通过NSwag.MSBuild完成Open API代码的生成和typescript代码生成(运用于Angular),其中一个让我很惊讶的是:他居然在项目编译的时候初始化了数据库,弄得我云里雾里。我修改连接字符串,从报错信息才知道是执行这部分脚本的时候,MSWage的内核里初始化了Core的项目,调用到了初始化数据库代码:

Executing file 'config.nswag' with variables 'Configuration=Debug'...
C:\Users\csuma.nuget\packages\nswag.msbuild\14.0.7\tools\Net80

下面是报错信息:

Error NSwag command line tool for .NET Core Net80, toolchain v14.0.7.0 (NJsonSchema v11.0.0.0 (Newtonsoft.Json v13.0.0.0));Visit http://NSwag.org for more information.;NSwag bin directory: C:\Users\csuma.nuget\packages\nswag.msbuild\14.0.7\tools\Net80;Executing file 'config.nswag' with variables 'Configuration=Debug'...;Launcher directory: C:\Users\csuma.nuget\packages\nswag.msbuild\14.0.7\tools\Net80;fail: CleanArchitecture.Infrastructure.Data.ApplicationDbContextInitialiser[0];An error occurred while initialising the database.;Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerDatabaseCreator.<>cDisplayClass20_0.<b0>d.MoveNext();--- End of stack trace from previous location ---;at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerDatabaseCreator.<>cDisplayClass20_0.<b0>d.MoveNext();--- End of stack trace from previous location ---;at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func4 operation, Func4 verifySucceeded, CancellationToken cancellationToken);at Microsoft.EntityFrameworkCore.Migrations.HistoryRepository.ExistsAsync(CancellationToken cancellationToken);at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.MigrateAsync(String targetMigration, CancellationToken cancellationToken);at CleanArchitecture.Infrastructure.Data.ApplicationDbContextInitialiser.InitialiseAsync() in D:\project\CleanArchitecture\CleanArchitecture-main\CleanArchitecture-main\src\Infrastructure\Data\ApplicationDbContextInitialiser.cs:line 46;at CleanArchitecture.Infrastructure.Data.InitialiserExtensions.InitialiseDatabaseAsync(WebApplication app) in D:\project\CleanArchitecture\CleanArchitecture-main\CleanArchitecture-main\src\Infrastructure\Data\ApplicationDbContextInitialiser.cs:line 21;at Program.

$(String[] args) in D:\project\CleanArchitecture\CleanArchitecture-main\CleanArchitecture-main\src\Web\Program.cs:line 17;at Program.
(String[] args);at System.RuntimeMethodHandle.InvokeMethod(Object target, Void** arguments, Signature sig, Boolean isConstructor);at System.Reflection.MethodBaseInvoker.InvokeDirectByRefWithFewArgs(Object obj, Span1 copyOfArgs, BindingFlags invokeAttr);ClientConnectionId:00000000-0000-0000-0000-000000000000;Error Number:-1,State:0,Class:20;--- End of inner exception stack trace ---;at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions);at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerDatabaseCreator.<>c__DisplayClass20_0.<<ExistsAsync>b__0>d.MoveNext();--- End of stack trace from previous location ---;at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func4 operation, FuncMARKDOWN_HASH33b582cf368b2b1a5719cf334009e4afMARKDOWNHASH1 copyOfArgs, BindingFlags invokeAttr);--- End of inner exception stack trace ---;at System.Reflection.MethodBaseInvoker.InvokeDirectByRefWithFewArgs(Object obj, Span`1 copyOfArgs, BindingFlags invokeAttr);at System.Reflection.MethodBaseInvoker.InvokeWithFewArgs(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture);at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters);at NSwag.AspNetCore.Launcher.Program.Main(String[] args) in //src/NSwag.AspNetCore.Launcher/Program.cs:line 132;System.InvalidOperationException: Swagger generation failed with non-zero exit code '1'.;at NSwag.Commands.Generation.AspNetCore.AspNetCoreToOpenApiCommand.RunAsync(CommandLineProcessor processor, IConsoleHost host) in //src/NSwag.Commands/Commands/Generation/AspNetCore/AspNetCoreToOpenApiCommand.cs:line 195;at NSwag.Commands.NSwagDocumentBase.GenerateSwaggerDocumentAsync() in //src/NSwag.Commands/NSwagDocumentBase.cs:line 270;at NSwag.Commands.NSwagDocument.ExecuteAsync() in //src/NSwag.Commands/NSwagDocument.cs:line 67;at NSwag.Commands.Document.ExecuteDocumentCommand.ExecuteDocumentAsync(IConsoleHost host, String filePath) in //src/NSwag.Commands/Commands/Document/ExecuteDocumentCommand.cs:line 76;at NSwag.Commands.Document.ExecuteDocumentCommand.RunAsync(CommandLineProcessor processor, IConsoleHost host) in //src/NSwag.Commands/Commands/Document/ExecuteDocumentCommand.cs:line 33;at NConsole.CommandLineProcessor.ProcessSingleAsync(String[] args, Object input);at NConsole.CommandLineProcessor.ProcessAsync(String[] args, Object input);at NSwag.Commands.NSwagCommandProcessor.ProcessAsync(String[] args) in //src/NSwag.Commands/NSwagCommandProcessor.cs:line 65 Web D:\project\CleanArchitecture\CleanArchitecture-main\CleanArchitecture-main\src\Web\Web.csproj 71

04
6

命令行执行NSwag

0
归档:2024年6月分类:C#和.NET

Important for .NET Core: Assembly loading#net-core

To use the command line tool nswag.exe (.NET 4.6+) / dotnet-nswag.dll (.NET Core), choose one of the following methods:

NSwag NPM Module: Bindings for the .NET 4.6+ and .NET Core command line tools (depending on installed framework/OS platform)
Download latest NSwagStudio MSI installer or install package NSwagStudio via Chocolatey: After installing the application, the path to the nswag.exe binary is registered in the PATH variable so that the tool can be used in the Windows command line.
Download the latest command line tools: Extract the ZIP archive and use the nswag.exe binary in the Windows command line.
NSwag.MSBuild NuGet package
To see all available commands and parameters, run the command line application "nswag.exe" without parameters and enter "help" as command. All "input" parameters accept file paths, URLs and JSON data.

Commands:

run: Executes an nswag.json config file (recommended)
aspnetcore2openapi: AspNetCoreToOpenApiCommand
webapi2openapi: WebApiToOpenApiCommand (should not be used for ASP.NET Core projects)
types2openapi: TypesToOpenApiCommand
openapi2csclient: CSharpClientCommand
openapi2cscontroller: CSharpControllerCommand
openapi2tsclient: TypeScriptClientCommand
Execute .nswag configuration document
An .nswag configuration document contains the instructions to generate/read a Swagger specification and generate code from it. The configuration document can be created with the NSwagStudio or manually by editing its JSON contents. To create a new nswag.json document in the current directory, use the new command:

nswag new
You can execute an .nswag configuration document by using the run command:

nswag run MySwaggerConfig.nswag
To run all .nswag configuration documents (*.nswag and nswag.json) in the current directory use the run command without parameters:

nswag run
Keep in mind that code generators are only executed when the output path is set.

Document variables
You can use variables in the document and replace them via command line. Just define use a variable in the document:

{
"defaultVariables": "Configuration=Debug",
"swaggerGenerator": {
"webApiToSwagger": {
"assemblyPaths": [
"bin/$(Configuration)/netcoreapp2.0/Apiverse.Web.dll"
],
You can define multiple variables by seperate key value pairs with a comma.

nswag run /variables:Configuration=Release,SecondVariable=true
As you can see, you can define the default variables with the defaultVariables properties and use it with $(MyVariable).

You can now replace the parameter via command line

nswag run /variables:Configuration=Release
With the NSwag.MSBuild package you can pass, the current Configuration to the document:

Swagger Generators
For ASP.NET Core apps, see AspNetCoreToOpenApiCommand

Deprecated
The following commands should not be used with ASP.NET Core

To generate a Swagger/OpenAPI specification from a Web API controller in a .NET assembly, see WebApiOpenApiDocumentGenerator for more information:

nswag webapi2openapi /assembly:MyWebApiAssembly.dll
/controller:MyNamespace.MyController
/output:MyWebService.json
To generate a single Swagger/OpenAPI specification for all controllers in the assembly, just call the command without the controller parameter:

nswag webapi2openapi /assembly:MyWebApiAssembly.dll
/output:MyWebService.json
The assembly parameter accepts multiple assemblies separated with a comma, e.g. /assembly:a1.dll,a2.dll.

To populate the info (title, description, version), host, basepath, and schemes data in your output file, use the following command line parameters:

nswag webapi2openapi /assembly:MyWebApiAssembly.dll
/output:MyWebService.json
/InfoTitle:MyWebService
/InfoVersion:V1
/InfoDescription:"My web service"
/ServiceHost:my.host.net
/ServiceBasePath:"/api"
/ServiceSchemes:"http,https"
WebApiToOpenApiCommand.cs

Client Generators
Generate TypeScript client code from a Swagger specification, see TypeScriptClientGenerator for more information:

nswag openapi2tsclient /input:MyWebService.json
/output:MyModule.ts
TypeScriptClientCommand.cs

Generate C# client code from a Swagger specification, see CSharpClientGenerator:

nswag openapi2csclient /input:MyWebService.json
/classname:MyServiceClient
/namespace:MyNamespace
/output:MyServiceClient.cs
CSharpClientCommand.cs

Generate Swagger from .NET types
Generate a Swagger/OpenAPI specification describing only the given .NET types:

nswag types2swagger /assembly:MyAssembly.dll
/classnames:MyNamespace.Person,MyNamespace.Car
/output:MySwagger.json
TypesToOpenApiCommand.cs

JSON Schema converters
Generate C# classes from a JSON Schema:

nswag jsonschema2csclient /input:JsonSchema.json
/output:MyClasses.cs
JsonSchemaToCSharpCommand.cs

Generate TypeScript interfaces from a JSON Schema:

nswag jsonschema2tsclient /input:JsonSchema.json
/output:MyInterfaces.ts
JsonSchemaToTypeScriptCommand.cs

Appendix: How to use UseDocumentProvider
Run a customized build and select the assembly in NSwagStudio, create an nswag.json and execute it via CLI (nswag run nswag.json):

04
6

NSwag.MSBuild使用

0
归档:2024年6月分类:C#和.NET

Package: NSwag.MSBuild

Important for .NET Core: Assembly loading#net-core

After installing the NSwag.MSBuild NuGet package in your project, you can use the variable $(NSwagExe) in your .csproj file to run the NSwag command line tool in an MSBuild target. This way the tools can easily be updated via NuGet. The /controller parameter can be omitted to generate a Swagger specification for all controllers.




For better testability and stable output (defaults may change), it is recommended to create an NSwag Configuration Document (e.g. with NSwagStudio) and use:



Recommended for .NET Core/NET5 and later:


OnBuildSuccess



For more information about the missing DLLs in .NET Core, see Assembly loading#net-core.

More information on nswag run.

Runtime:

If you need to run the NSwag command line in x86 mode, use the $(NSwagExe_x86) placeholder. For .NET Core projects, one of the placeholders $(NSwagExe_Core##) or $(NSwagExe_Net##) (e.g. $(NSwagExe_Core31) for .NET Core 3.1) should be used instead of $(NSwagExe).

Available properties:

NSwagExe
NSwagExe_x86
NSwagExe_Core21
NSwagExe_Core31
NSwagExe_Net50
NSwagExe_Net60
NSwagExe_Net70
NSwagDir
NSwagDir_Core21
NSwagDir_Core31
NSwagDir_Net50
NSwagDir_Net60
NSwagDir_Net70
NSwag.MSBuild.props

See Command Line for more information.

Also see ServiceProjectReference for the new feature.

04
6

MSBuild介绍

0
归档:2024年6月分类:C#和.NET

Microsoft 生成引擎是一个用于生成应用程序的平台。 此引擎(也称为 MSBuild)为项目文件提供了一个 XML 架构,用于控制生成平台处理和生成软件的方式。 Visual Studio 会使用 MSBuild,但 MSBuild 不依赖于 Visual Studio。 通过在项目或解决方案文件中调用 msbuild.exe 或 dotnet build,可以在未安装 Visual Studio 的环境中安排和生成产品。

Visual Studio 使用 MSBuild 来加载和生成托管项目。 Visual Studio 中的项目文件(.csproj、.vbproj、vcxproj 等)包含 MSBuild XML 代码,当你使用 IDE 来生成项目时,此代码就会运行。 Visual Studio 项目会导入所有必要的设置和生成过程来执行典型的开发工作,但你可以从 Visual Studio 内或通过使用 XML 编辑器对其进行扩展或修改。

若要在没有 Visual Studio 的 Windows 系统上安装 MSBuild,请转到下载页面上的 Visual Studio 生成工具。 通过此方法安装 MSBuild 可获得 MSBuild.exe。

对于 .NET Core 和 .NET 5 或更高版本,获取 MSBuild 等效项的另一种方法是安装 .NET SDK。 .NET 生成命令 dotnet build 可与 macOS、Windows 或 Linux 上的 .NET SDK 一起使用。 .NET 生成命令 dotnet build 是 .NET Core 版本 MSBuild.exe 的精简包装器。 可以使用 .NET Core 命令行接口 (CLI)(使用 MSBuild)来生成面向 .NET Core 和 .NET 5 及更高版本的项目。

从 Visual Studio 2022 开始,当你在 Visual Studio 中生成时,将使用 64 位版本的 MSBuild。

有关适用于 C++ 的 MSBuild 的信息,请参阅 MSBuild (C++)。

下面的示例介绍了什么情况下可从命令行调用 MSBuild 而不是 Visual Studio IDE 来运行生成。

未安装 Visual Studio。

你需要使用 64 位版本的 MSBuild,你现在使用的是 Visual Studio 2019 或更早版本。 通常情况下不必使用此版本的 MSBuild,但它可以让 MSBuild 访问更多内存。

你想要在多个进程中运行同一生成。 不过,对于 C++ 和 C# 中的项目,你可以使用 IDE 实现相同的结果。

你想要修改生成系统。 例如,你可能想要实现以下操作:

在文件到达编译器之前先进行预处理。

将生成输出复制到其他位置。

从生成输出创建压缩文件。

执行后处理步骤。 例如,你可能希望使用其他版本来标记程序集。

你可以在 Visual Studio IDE 中编写代码,但使用 MSBuild 来运行生成。 或者,你也可以在开发计算机的 IDE 中生成代码,但从命令行运行 MSBuild,以在多个开发人员的协作下生成从源存储库集成的代码。

备注

你可以使用 Azure Pipelines 自动编译、测试和部署应用程序。 你的生成系统会在开发人员签入代码(例如,作为持续集成策略的一部分)时或按照计划(例如,夜间版本验证测试生成)自动运行生成。 Azure Pipelines 使用 MSBuild 来编译代码。 有关详细信息,请参阅 Azure Pipelines。

有关 Windows 上的 MSBuild 的介绍性教程,请参阅演练:使用 MSBuild。

在命令提示符处使用 MSBuild
若要在命令提示符处运行 MSBuild,请将项目文件随相应的命令行选项一起传递到 MSBuild.exe。 命令行选项允许你设置属性、执行特定的目标,以及设置可控制生成过程的其他选项。 例如,使用以下命令行语法生成文件 MyProj.proj,并将 Configuration 属性设置为 Debug。

Windows 命令提示符

复制
MSBuild.exe MyProj.proj -property:Configuration=Debug
MSBuild 不会根据文件扩展名更改其行为,但惯例是使用以proj结尾的扩展,如.csproj、.vcxproj或.vbproj,为名为“项目文件”的主 MSBuild 输入文件。

有关 MSBuild 命令行选项的详细信息,请参阅命令行参考。

重要

在下载项目之前,请确定代码的可信度。

对于 .NET Core 和 .NET 5 或更高版本,通常使用 dotnet build 调用 MSBuild。 请参阅 dotnet build。 如果仅安装 .NET SDK,而不安装 Visual Studio 或 Visual Studio 生成工具,则只能通过 dotnet build 安装 MSBuild。

命令行 dotnet build --help 列出了特定于 dotnet build 的命令行选项,而不是 MSBuild.exe 的所有选项,但你仍然可以使用 MSBuild 命令行参考中列出的所有命令行选项。 dotnet build 未处理的选项将传递给 MSBuild。

项目文件
MSBuild 使用简单且可扩展的基于 XML 的项目文件格式。 使用 MSBuild 项目文件格式,开发人员可以描述要生成的项,以及如何针对不同的操作系统和配置生成这些项。 另外,这种项目文件格式还允许开发人员创作可重用的生成规则,这些规则可以包含到不同的文件中,以便可以在产品内的不同项目之间一致地执行生成。

Visual Studio 生成系统将项目特定的逻辑存储在项目文件中,并使用导入的 MSBuild XML 文件(扩展名为 .props 和 .targets 等)来定义标准生成逻辑。 .props 文件定义 MSBuild 属性,而 .targets 文件定义 MSBuild 目标。 这些导入内容有时在 Visual Studio 项目文件中可见,但在 .NET Core、.NET 5 和 .NET 6 项目等较新的项目中,项目文件不显示导入内容;而是显示 SDK 引用,如下所示:

XML

复制


这些项目称为 SDK 风格的项目。 当你引用 SDK(如 .NET SDK)时,SDK 会隐式指定 .props 和 .target 文件的导入内容。

以下各节介绍了 MSBuild 项目文件格式的一些基本元素。 有关如何创建基本项目文件的教程,请参见演练:从头开始创建 MSBuild 项目文件。

属性
属性表示可用于配置生成的键/值对。 属性的声明方式是:创建一个与属性同名的元素,将其指定为 PropertyGroup 元素的子元素。 例如,下面的代码将创建一个名为 BuildDir 的属性,其值为 Build。

XML

复制

Build

通过在元素中放置一个 Condition 属性,你可以有条件地定义一个属性。 除非条件的计算结果为 true,否则会忽略条件元素的内容。 在下面的示例中,将定义 Configuration 属性(如果尚未定义)。

XML

复制
DefaultValue
在整个项目文件中,可以使用语法 $ () 来引用各个属性。 例如,可以使用 $(BuildDir) 和 $(Configuration) 来引用前面示例中的属性。

有关属性的详细信息,请参阅 MSBuild 属性。

项目
项是生成系统的输入,通常表示文件。 将根据用户定义的项名称,将项编组到各种项类型中。 这些项类型可以用作任务的参数,任务使用各个项来执行生成过程的步骤。

项目文件中项的声明方法是:通过创建一个与项类型同名的元素,并将其指定为 ItemGroup 元素的子元素。 例如,下面的代码将创建一个名为 Compile 的项类型,其中包括两个文件。

XML

复制




在整个项目文件中,可以使用语法 @() 来引用项类型。 例如,可以使用 @(Compile) 引用示例中的项类型。

在 MSBuild 中,元素和特性名称区分大小写。 但是,属性、项和元数据名称不区分大小写。 下面的示例创建了项类型 Compile、comPile 或任何其他大小写变体,并为其指定了值“one.cs;two.cs”。

XML

复制




可以使用通配符声明项,并且对于更高级的生成方案,项可以包含其他元数据。 有关项的详细信息,请参阅项。

任务
任务是 MSBuild 项目用于执行生成操作的可执行代码单元。 例如,任务可能编译输入文件或运行外部工具。 任务可以重用,并且可由不同项目中的不同开发人员共享。

任务的执行逻辑在托管代码中编写,并使用 UsingTask 元素映射到 MSBuild。 你可以通过创作一个实现 ITask 接口的托管类型来编写自己的任务。 有关如何编写任务的详细信息,请参阅任务写入。

MSBuild 包含一些可按需进行修改的常见任务。 例如,用于复制文件的复制、用于创建目录的 MakeDir 以及用于编译 Visual C# 源代码文件的 Csc。 有关可用任务的列表以及用法信息,请参阅任务参考。

通过创建一个与任务同名的元素,并将其指定为 Target 元素的子元素,可以在 MSBuild 项目文件中执行此任务。 任务通常接受参数,参数将作为元素的特性进行传递。 MSBuild 的属性和项都可用作参数。 例如,以下代码将调用 MakeDir 任务,并将前面示例中声明的 BuildDir 属性的值传递到该任务。

XML

复制



有关任务的详细信息,请参阅任务。

目标
目标按特定的顺序将任务组合到一起,并将项目文件的各个部分公开为生成过程的入口点。 目标通常分组到各个逻辑部分中,以便提高可读性并实现扩展。 通过将生成步骤拆分为目标,你可以从其他目标中调用生成过程的一个部分,而不必将那部分代码复制到每个目标中。 例如,如果生成过程的多个入口点需要生成引用,你可以创建一个生成引用的目标,然后从所要求的每个入口点运行此目标。

目标是使用 Target 元素在项目文件中声明的。 例如,以下代码将创建一个名为 Compile 的目标,该目标随后将调用具有前面示例中声明的项列表的 Csc 任务。

XML

复制



在更高级的方案中,目标可用于描述彼此之间的关系并执行依赖性分析,这样,如果目标是最新的,则可以跳过生成过程的整个部分。 有关目标的更多信息,请参阅目标。

生成日志
你可以将生成错误、警告和消息记录到控制台或其他输出设备。 有关详细信息,请参阅使用 MSBuild 获取生成日志。

在 Visual Studio 中使用 MSBuild
Visual Studio 使用 MSBuild 项目文件格式存储有关托管项目的生成信息。 通过使用 Visual Studio 接口添加或更改的项目设置将反映在为每个项目生成的 .*proj 文件中。 Visual Studio 使用 MSBuild 的一个托管实例来生成托管项目。 这意味着可以在 Visual Studio 中或在命令提示符处生成托管项目(即使未安装 Visual Studio),并且结果将完全相同。

有关如何在 Visual Studio 中使用 MSBuild 的教程,请参阅演练:使用 MSBuild。

多目标
通过使用 Visual Studio,可以编译应用程序,使其能够在多个版本的 .NET Framework 或 .NET Core(包括 .NET 5 和更高版本)上运行。 例如,可以将同一个应用程序编译为既能在 32 位平台的 .NET Framework 4 上运行,也能在 64 位平台的 .NET Framework 4.8 上运行。 这种使用多个框架作为编译目标的能力称为“多目标功能”。

以下是多目标功能的一些优点:

可以开发以多个 .NET Framework 早期版本(例如,版本 3.5 和 4.7.2)为目标的应用程序。

可以一个框架配置文件为目标,该文件是目标框架的预定义子集。

如果已发布 .NET Framework 当前版本的服务包,则可以将其作为目标。

多目标功能可以保证应用程序仅使用目标框架和平台中的可用功能。

有关详细信息,请参阅多定向。

自定义生成
MSBuild 为多种自定义生成方案提供了支持。 大多数内置功能都可以重写或扩展。 请参阅自定义生成。

以编程方式访问 MSBuild
如果要开发生成工具,可能需要以编程方式从 .NET 应用程序调用 MSBuild。 通过使用 MSBuild API,可以控制复杂生成系统的所有方面。 MSBuild 提供了具有完整 API(Microsoft.Build 命名空间)的 NuGet 包,你可从 .NET 应用程序将其用于这些目的。 请参阅使用 MSBuild API。

MSBuild 是开源的
MSBuild 是一种接受用户贡献的开源项目,就像 .NET 生态系统的其余部分一样。 GitHub 中提供了包含 MSBuild 源的存储库:MSBuild GitHub 存储库。

04
6

NSwag 和 ASP.NET Core 入门

0
归档:2024年6月分类:C#和.NET

NSwag 提供了下列功能:

能够使用 Swagger UI 和 Swagger 生成器。
灵活的代码生成功能。
借助 NSwag,无需使用现有 API。也就是说,可使用包含 Swagger 的第三方 API,并生成客户端实现。 使用 NSwag,可以加快开发周期,并轻松适应 API 更改。

包安装
将 NSwag 安装到:

生成已实现的 Web API 的 Swagger 规范。
为 Swagger UI 提供服务以浏览和测试 Web API。
为 Redoc 提供服务,以为 Web API 添加 API 文档。
若要使用 NSwag ASP.NET Core 中间件,请安装 NSwag.AspNetCore NuGet 包。 此包内的中间件可用于生成并提供Swagger 规范、Swagger UI(v2 和 v3)和 ReDoc UI。 NSwag 14 仅支持 v3 版的 Swagger UI 规范。

若要安装 NSwag NuGet 包,请使用以下方法之一:

Visual Studio
Visual Studio for Mac
Visual Studio Code
.NET CLI
从“程序包管理器控制台”窗口:

转到“视图”>“其他窗口”>“程序包管理器控制台”

导航到包含 NSwagSample.csproj 文件的目录

请执行以下命令:

PowerShell

复制
Install-Package NSwag.AspNetCore
从“管理 NuGet 程序包”对话框中:

右键单击“解决方案资源管理器”>“管理 NuGet 包”中的项目
将“包源”设置为“nuget.org”
在搜索框中输入“NSwag.AspNetCore”
从“浏览”选项卡中选择“NSwag.AspNetCore”包,然后单击“安装”
添加并配置 Swagger 中间件
通过执行以下步骤,在 ASP.NET Core 应用中添加和配置 Swagger:

将 OpenApi 生成器添加到 Program.cs 中的服务集合:
C#

复制
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
builder.Services.AddOpenApiDocument();
启用中间件来提供生成的 OpenApi 规范、Swagger UI 和 Redoc UI,同时在 Program.cs 中:
C#

复制
if (app.Environment.IsDevelopment())
{
// Add OpenAPI 3.0 document serving middleware
// Available at: http://localhost:/swagger/v1/swagger.json
app.UseOpenApi();

// Add web UIs to interact with the document
// Available at: http://localhost:/swagger
app.UseSwaggerUi(); // UseSwaggerUI Protected by if (env.IsDevelopment())

}
启动应用。 转到:
http://localhost:/swagger,以查看 Swagger UI。
http://localhost:/swagger/v1/swagger.json,以查看 Swagger 规范。
代码生成
若要利用 NSwag 的代码生成功能,可选择以下选项之一:

NSwagStudio:一款 Windows 桌面应用,用于在 C# 或 TypeScript 中生成 API 客户端代码。
NSwag.CodeGeneration.CSharp 或 NSwag.CodeGeneration.TypeScript NuGet 包 - 用于在项目中生成代码。
通过命令行使用 NSwag。
NSwag.MSBuild NuGet 包。
Unchase OpenAPI (Swagger) Connected Service(Unchase OpenAPI (Swagger) 连接服务):一种 Visual Studio 连接服务,用于在 C# 或 TypeScript 中生成 API 客户端代码。 还可以使用 NSwag 为 OpenAPI 服务生成 C# 控制器。
使用 NSwagStudio 生成代码
按照 NSwagStudio GitHub 存储库中的说明操作,以安装 NSwagStudio。 在 NSwag 发布页面上,可以下载无需安装和管理员权限即可启动的 xcopy 版本。
启动 NSwagStudio,并在“Swagger 规范 URL”文本框中输入 swagger.json 文件 URL。 例如 http://localhost:5232/swagger/v1/swagger.json
单击“创建本地副本”按钮,以生成 Swagger 规范的 JSON 表示形式。
NSwag Studio 导入规范并导出 CSharp 客户端。

在“输出”区域中,单击“CSharp 客户端”复选框。 也可以选中“TypeScript 客户端”或“C# Web API 控制器”,具体视项目而定。 如果选中“C# Web API 控制器”,服务规范会重新生成服务,起到反向生成的作用。
单击“生成输出”,以生成 TodoApi.NSwag 项目的完整 C# 客户端实现。 若要查看生成的客户端代码,请单击“C# 客户端”选项卡:
C#

复制
namespace MyNamespace
{
using System = global::System;

[System.CodeDom.Compiler.GeneratedCode("NSwag", "14.0.1.0 (NJsonSchema v11.0.0.0 (Newtonsoft.Json v13.0.0.0))")]
public partial class TodoClient
{
#pragma warning disable 8618 // Set by constructor via BaseUrl property
    private string _baseUrl;
#pragma warning restore 8618 // Set by constructor via BaseUrl property
    private System.Net.Http.HttpClient _httpClient;
    private static System.Lazy _settings = new System.Lazy(CreateSerializerSettings, true);

    public TodoClient(System.Net.Http.HttpClient httpClient)
    {
        BaseUrl = "http://localhost:5232";
        _httpClient = httpClient;
    }

    private static Newtonsoft.Json.JsonSerializerSettings CreateSerializerSettings()
    {
        var settings = new Newtonsoft.Json.JsonSerializerSettings();
        UpdateJsonSerializerSettings(settings);
        return settings;
    }

    public string BaseUrl
    {
        get { return _baseUrl; }
        set
        {
            _baseUrl = value;
            if (!string.IsNullOrEmpty(_baseUrl) && !_baseUrl.EndsWith("/"))
                _baseUrl += '/';
        }
    }
    // code omitted for brevity

提示

C# 客户端代码的生成依据是,“设置”选项卡中的选择。修改设置以执行任务,例如默认命名空间重命名和同步方法生成。

将生成的 C# 代码复制到使用 API 的客户端项目内的文件中。
开始使用 Web API:
C#

复制
var todoClient = new TodoClient(new HttpClient());

// Gets all to-dos from the API
var allTodos = await todoClient.GetAsync();

// Create a new TodoItem, and save it via the API.
await todoClient.CreateAsync(new TodoItem());

// Get a single to-do by ID
var foundTodo = await todoClient.GetByIdAsync(1);

03
6

解决ng : 无法将“ng”项识别为 cmdlet、函数、脚本文件或可运行程序的名称 及 ng : 无法加载文件 C:\Users\15762\AppData\Roaming\npm\ng.ps1问题
ng : 无法将“ng”项识别为 cmdlet、函数、脚本文件或可运行程序的名称
解决 在命令行执行npm install -g @angular/cli
ng : 无法加载文件 C:\Users\15762\AppData\Roaming\npm\ng.ps1
解决 以管理员身份运行Windows PowerShell,输入set-ExecutionPolicy RemoteSigned 选择是选择 A

ng : 无法将“ng”项识别为 cmdlet、函数、脚本文件或可运行程序的名称

解决 在命令行执行npm install -g @angular/cli

ng : 无法加载文件 C:\Users\15762\AppData\Roaming\npm\ng.ps1

解决 以管理员身份运行Windows PowerShell,输入set-ExecutionPolicy RemoteSigned 选择是选择 A

01
6

Visual Studio 2022.http 文件编辑器提供了一种便捷的方式来测试 ASP.NET Core项目,尤其是 API 应用。 编辑器提供一个 UI,用于:

创建和更新 .http 文件。
发送 .http 文件中指定的 HTTP 请求。
显示响应。
本文包含以下文档:

.http 文件语法。
如何创建 .http 文件。
如何从 .http 文件发送请求。
在何处查找可配置的 .http 文件选项。
如何使用 Visual Studio 2022 终结点资源管理器在 .http 文件中创建请求。
.http 文件格式和编辑器受 Visual Studio Code REST 客户端扩展的启发。 Visual Studio 2022 .http 编辑器将 .rest 识别为相同文件格式的替代文件扩展名。

先决条件
安装了“ASP.NET 和 Web 部署”工作负载的 Visual Studio 2022 版本 17.8 或更高版本。
.http 文件语法
以下部分介绍 .http 文件语法。

请求
HTTP 请求的格式为 HTTPMethod URL HTTPVersion,全部在一行上,其中:

HTTPMethod 是要使用的 HTTP 方法,例如:
OPTIONS
GET
HEAD
POST
PUT
PATCH
DELETE
TRACE
CONNECT
URL 是向其发送请求的 URL。 此 URL 可以包括查询字符串参数。 此 URL 不必指向本地 Web 项目。 它可以指向 Visual Studio 可以访问的任何 URL。
HTTPVersion 是可选的,指定应使用的 HTTP 版本,即 HTTP/1.1、HTTP/2 或 HTTP/3。
通过使用行 ### 作为分隔符,文件可以包含多个请求。 以下示例在一个文件中显示了三个请求,说明了此语法:
复制
GET https://localhost:7220/weatherforecast

GET https://localhost:7220/weatherforecast?date=2023-05-11&location=98006

GET https://localhost:7220/weatherforecast HTTP/3

请求标头
若要添加一个或多个标头,请将每个标头立即添加到请求行后其自己的行中。 不要在请求行与第一个标头之间或后续标头行之间包含任何空白行。 格式为 HeaderName: Value,如以下示例所示:

HTTP

复制
GET https://localhost:7220/weatherforecast
Date: Wed, 27 Apr 2023 07:28:00 GMT

GET https://localhost:7220/weatherforecast
Cache-Control: max-age=604800
Age: 100

重要

调用使用标头进行身份验证的 API 时,请勿将任何机密提交到源代码存储库。 请参阅本文后面的支持存储机密的方法,例如 ASP.NET Core 用户机密、Azure Key Vault 和 DPAPI 加密。

请求正文
在空白行后面添加请求正文,如以下示例所示:

POST https://localhost:7220/weatherforecast
Content-Type: application/json
Accept-Language: en-US,en;q=0.5

{
"date": "2023-05-10",
"temperatureC": 30,
"summary": "Warm"
}

注释
以 # 或 // 开头的行是注释。 当 Visual Studio 发送 HTTP 请求时,将忽略这些行。

变量
以 @ 开头的行使用语法 @VariableName=Value 定义变量。

可以在稍后在文件中定义的请求中引用变量。 通过用双大括号括起名称 {{ 和 }} 来引用它们。 以下示例演示在请求中定义和使用的两个变量:

@hostname=localhost
@port=44320
GET https://{{hostname}}:{{port}}/weatherforecast
可以使用文件前面定义的其他变量的值来定义变量。 以下示例在请求中使用一个变量,而不是前面示例中所示的两个变量:

@hostname=localhost
@port=44320
@host={{hostname}}:{{port}}
GET https://{{host}}/api/search/tool
环境文件
若要在不同的环境中为变量提供不同的值,请创建名为 http-client.env.json 的文件。 在 .http 文件所在的同一目录中或其中一个父目录中找到该文件。 下面是环境文件的示例:

{
"dev": {
"HostAddress": "https://localhost:44320"
},
"remote": {
"HostAddress": "https://contoso.com"
}
}

环境文件是一个 JSON 文件,其中包含一个或多个命名环境,如前面的示例中的“dev”和“remote”。 每个命名环境都包含一个或多个变量,例如前面的示例中的 HostAddress。 从环境文件中引用变量的方式与其他变量相同,如以下示例所示:

HTTP
GET {{HostAddress}}/api/search/tool

发送请求时用于变量的值由 .http 文件编辑器右上角的环境选择器下拉列表确定。 以下屏幕截图显示了选择器:

.http file editor with environment selector highlighted. The 'dev' environment is selected.

环境文件不必位于项目文件夹中。 Visual Studio 在 .http 文件所在的文件夹中查找环境文件。 如果它不在该文件夹中,Visual Studio 会浏览父目录来查找它。 找到名为 http-client.env.json 的文件后,搜索将结束。 将使用最接近 .http 文件的文件。

创建或编辑 .http 文件后,可能需要关闭并重新打开项目,以查看环境选择器中反映的更改。 按 F6 选择环境选择器。

Visual Studio 在以下情况下显示警告:

.http 文件引用了未在 .http 文件或环境文件中定义的变量。环境文件包含 .http 文件中未引用的变量。在环境文件中定义的变量可以与 .http 文件中定义的变量相同,也可以不同。 如果在 .http 文件和环境文件中都定义了变量,则 .http 文件中的值将替代环境文件中的值。

10
5

Orchard Core 中文文档

0
归档:2024年5月分类:C#和.NET

Orchard Core 是基于 Orchard CMS 使用 ASP.NET Core 重新构建的。

Orchard Core 由两个不同的目标组成:

Orchard Core Framework: 一个应用程序框架,用于构建模块化、多租户 的ASP.NET Core应用程序。
Orchard Core CMS: 一个建立在Orchard Core Framework之上的网络内容管理系统(CMS)。

需要注意框架和 CMS 之间的差异非常重要。一些想要开发 SaaS 应用程序的开发人员只会对模块化框架感兴趣。其他想要构建可管理网站的用户将专注于 CMS 并构建模块来增强其网站或整个生态系统。

Building Software as a Service (SaaS) solutions with the Orchard Core Framework

了解Orchard Core Framework是独立于nuget.org上的CMS分发的,这一点非常重要。我们在 https://github.com/OrchardCMS/OrchardCore.Samples 提供了一些示例程序,它将指导您如何仅使用Orchard Core Framework来构建模块化 和 多租户 的应用程序,而无需任何 CMS 特定功能。

我们的目标之一是启用托管应用程序的基于社区的生态系统,这些生态系统可以通过模块(如电子商务系统、博客引擎等)进行扩展。Orchard Core Framework支持模块化环境,允许不同的团队处理应用程序的不同部分,并使组件跨项目可重用。

B站演示视频:https://www.bilibili.com/video/BV17T4y177fW/

使用Orchard Core CMS 构建网站

Orchard Core CMS 是基于Orchard CMS 使用ASP.NET Core 重写的。它不仅仅是一个端口,因为我们希望大幅提高性能,并尽可能与的ASP.NET Core 的开发模型一致。

性能. 这可能是开始使用Orchard Core CMS时最明显的变化。这对CMS来说是非常快的。速度如此之快,以至于我们甚至都没有关心输出缓存模块的工作。让你体验一下,没有缓存的Orchard Core CMS比以前的版本快了20倍。

跨平台. 现在,您可以在 Windows、Linux 和 macOS 上开发和部署Orchard Core CMS。我们也有 Docker 映像可供使用。

文档数据库 抽象化. Orchard Core CMS仍然需要一个关系数据库,并且兼容SQL Server, MySQL, PostgreSQL和SQLite,但是它现在使用的是一个抽象化文档数据库(YesSql),它提供了一个文档数据库API来存储和查询文档。对于CMS系统来说,这是一种更好的方法,可以显著提高性能。

NuGet 包. 模块和主题现在作为NuGet包共享。用Orchard Core CMS创建一个新网站其实很简单,只需从NuGet gallery引用一个元包。它还意味着更新到一个新的版本只涉及更新这个包的版本号。

实时预览. 在编辑内容项时,甚至在保存内容之前,就可以实时看到它在站点上的样子。它也适用于模板,您可以浏览任何页面,在您键入更改时检查更改对模板的影响。

Liquid 模板支持. 编辑者可以使用Liquid模板语言安全地更改HTML模板。 选择它的原因在于它有据可查(Jekyll,Shopify等),又非常安全。

自定义查询. 我们希望为开发人员提供一种尽可能简单地访问他们所有数据的方式。我们创建了一个模块,允许您创建自定义临时 SQL 和 Lucene 查询,这些查询可用于重新显示自定义内容或公开为 API 终结点。您可以使用它创建高效的查询,或将数据公开给 SPA 应用程序。

部署计划. 部署计划是可以包含构建网站的内容和元数据的脚本。您现在可以包含二进制文件,甚至可以使用它们来远程部署站点,例如从准备环境部署到生产环境。它们也可以是NuGet软件包的一部分,允许你发送预定义的网站。

可伸缩性. 由于 Orchard Core 是一个多租户系统,因此您可以通过单个部署托管尽可能多的网站。然后,典型的云计算机可以并行承载数千个站点,包括数据库、内容、主题和用户隔离。

工作流. 创建内容审批工作流、响应 Webhook、在提交表单时执行操作,以及要使用用户友好的 UI 实现的任何其他流程。

GraphQL.我们提供非常灵活的 GraphQL API,以便任何授权的外部应用程序都可以重用您的内容,如 SPA 应用程序或静态站点生成器。

不同的网站构建策略

Orchard Core CMS支持所有主要的网站建设策略:

完整 CMS. 在此模式下,网站使用主题和模板来呈现您的内容,旨在实现很少或完全没有自定义开发。

解耦 CMS(Decoupled CMS). 除了内容管理端之外,网站从空白开始。您可以使用 Razor Pages 或 MVC 操作创建所需的所有模板,并通过内容服务访问您的内容。

无头 CMS(Headless CMS). 该网站只管理内容,您创建一个单独的应用程序,该应用程序将使用 GraphQL 或 REST API 获取托管内容。参考: B站,油管

The latest released version of Orchard Core is 1.5.0. The release notes can be found on https://github.com/OrchardCMS/OrchardCore/releases/tag/v1.5.0

该软件几乎已准备好最终发布。 不进行功能开发或软件增强; 在此阶段仅允许严格限定范围的错误修复,除非出现重大的错误。

这是一个更详细的路线图.

Clone the repository using the command git clone https://github.com/OrchardCMS/OrchardCore.git and checkout the main branch for the latest release, or the dev branch for the cutting-edge version.

使用命令 git clone https://github.com/OrchardCMS/OrchardCore.git 克隆此仓库,并切换到 main 分支。

按照这个教程 Training Demo Module 你将学习如何开发Orchard Core模块。(这里是包含中文翻译的版本:码云仓库,含全部中文注释)
观看Orchard Core演示的ASP.NET社区站立视频:B站 youtube
参考这个示例 https://github.com/OrchardCMS/OrchardCore.Samples 它将引导你如何构建一个 模块化 和 多租户 的应用程序。

命令行
Install the latest version of the .NET SDK from this page https://dotnet.microsoft.com/download
Next, navigate to D:\OrchardCore\src\OrchardCore.Cms.Web or wherever your folder is on the commandline in Administrator mode.
Call dotnet run.
Then open the http://localhost:5000 URL in your browser.
你也可以参考 代码生成模板文档 从预定义的模板创建新的应用程序。

Visual Studio

For more details on the various development tools we recommend for using with Orchard Core check out the Development Tools documentation page.

Download Visual Studio 2022 (any edition) from https://www.visualstudio.com/downloads/.
Open OrchardCore.sln and wait for Visual Studio to restore all Nuget packages.

Ensure OrchardCore.Cms.Web is the startup project and run it.
Optionally install the Lombiq Orchard Visual Studio Extension to add some useful utilities to your Visual Studio such as an error log watcher or a dependency injector.
Optionally install the code snippets from the Orchard Dojo Library to quickly generate code in some common scenarios during module and theme development.

Docker

运行 docker run --name orchardcms orchardproject/orchardcore-cms-linux:latest
Docker images and parameters can be found at https://hub.docker.com/u/orchardproject/

公告栏

欢迎大家来到我的博客,我是dodoro,希望我的博客能给你带来帮助。