├── .editorconfig
├── .gitattributes
├── .github
└── workflows
│ └── dotnetcore.yml
├── .gitignore
├── DotNet.Cli.Build
├── DotNet.Cli.Build.csproj
├── Exe.cs
├── Project.cs
└── Resources
│ └── DotNetCliBuild.targets
├── GenerateAspNetCoreClient.Command
├── ClientModelBuilder.cs
├── Extensions
│ ├── ObjectExtensions.cs
│ ├── StringExtensions.cs
│ └── TypeExtensions.cs
├── GenerateAspNetCoreClient.Command.csproj
├── GenerateClientCommand.cs
├── GroupInfo.cs
├── HostFactoryResolver.cs
├── Model
│ ├── Client.cs
│ ├── EndpointMethod.cs
│ ├── Parameter.cs
│ └── ParameterSource.cs
├── Properties
│ └── Assembly.cs
└── ServiceProviderResolver.cs
├── GenerateAspNetCoreClient.Options
├── GenerateAspNetCoreClient.Options.csproj
└── GenerateClientOptions.cs
├── GenerateAspNetCoreClient.sln
├── GenerateAspNetCoreClient
├── CustomLoadContext.cs
├── GenerateAspNetCoreClient.csproj
├── Program.cs
└── Properties
│ ├── Assembly.cs
│ └── launchSettings.json
├── LICENSE
├── README.md
└── Tests
├── GenerateAspNetCoreClient.Tests
├── ApiDescriptionTestData.cs
├── ClientGenerationTests.GenerationTest_UseApiResponses
│ └── IWeatherForecastApi.verified.cs
├── ClientGenerationTests.GenerationTest_UseApiResponses_UseCancellationTokens
│ ├── ITestWebApiMinimalApiApi.verified.cs
│ └── IWeatherForecastApi.verified.cs
├── ClientGenerationTests.GenerationTest_testProjectName=TestWebApi.Controllers
│ ├── IAnotherTestApi.verified.cs
│ └── IWeatherForecastApi.verified.cs
├── ClientGenerationTests.GenerationTest_testProjectName=TestWebApi.MinimalApi
│ ├── ITestWebApiMinimalApiApi.verified.cs
│ └── IWeatherForecastApi.verified.cs
├── ClientGenerationTests.GenerationTest_testProjectName=TestWebApi.Versioning
│ └── IVersionApi.verified.cs
├── ClientGenerationTests.cs
├── ClientModelBuilderTests.cs
├── EndpointFilteringTests.cs
└── GenerateAspNetCoreClient.Tests.csproj
├── OutputTest
└── OutputProject.csproj
├── TestWebApi.Controllers.UseApiResponses
├── Controllers
│ └── WeatherForecastController.cs
├── Program.cs
├── Properties
│ └── launchSettings.json
├── TestWebApi.Controllers.UseApiResponses.csproj
├── appsettings.Development.json
└── appsettings.json
├── TestWebApi.Controllers
├── .editorconfig
├── Controllers
│ ├── AnotherTestController.cs
│ └── WeatherForecastController.cs
├── Program.cs
├── Properties
│ └── launchSettings.json
├── Startup.cs
├── TestWebApi.Controllers.csproj
├── appsettings.Development.json
└── appsettings.json
├── TestWebApi.Dtos
├── RecordModel.cs
├── SomeEnum.cs
├── SomeQueryModel.cs
├── TestWebApi.Dtos.csproj
├── WeatherForecast.cs
└── WeatherForecastRecord.cs
├── TestWebApi.MinimalApi
├── Program.cs
├── Properties
│ └── launchSettings.json
├── TestWebApi.MinimalApi.csproj
├── appsettings.Development.json
└── appsettings.json
└── TestWebApi.Versioning
├── Controllers
└── VersionController.cs
├── Program.cs
├── Properties
└── launchSettings.json
├── TestWebApi.Versioning.csproj
├── appsettings.Development.json
└── appsettings.json
/.editorconfig:
--------------------------------------------------------------------------------
1 | [*.cs]
2 |
3 | indent_style = space
4 | csharp_indent_case_contents = true
5 | csharp_indent_switch_labels = true
6 | csharp_new_line_before_catch = true
7 | csharp_new_line_before_else = true
8 | csharp_new_line_before_finally = true
9 | csharp_new_line_before_members_in_object_initializers = true
10 | csharp_new_line_before_open_brace = methods, lambdas, object_collection_array_initializers, control_blocks, types
11 | dotnet_sort_system_directives_first = true
12 | csharp_space_after_cast = false
13 | csharp_space_after_colon_in_inheritance_clause = true
14 | csharp_space_after_keywords_in_control_flow_statements = true
15 | csharp_space_before_colon_in_inheritance_clause = true
16 | csharp_space_between_method_call_empty_parameter_list_parentheses = false
17 | csharp_space_between_method_call_name_and_opening_parenthesis = false
18 | csharp_space_between_method_call_parameter_list_parentheses = false
19 | csharp_space_between_method_declaration_empty_parameter_list_parentheses = false
20 | csharp_space_between_method_declaration_parameter_list_parentheses = false
21 | csharp_preserve_single_line_blocks = true
22 | csharp_prefer_braces = true : silent
23 | csharp_style_expression_bodied_constructors = false : silent
24 | csharp_style_expression_bodied_methods = false : silent
25 | csharp_style_expression_bodied_properties = true : silent
26 | csharp_style_inlined_variable_declaration = true : suggestion
27 | dotnet_style_predefined_type_for_member_access = true : suggestion
28 | dotnet_style_object_initializer = true : suggestion
29 | csharp_style_var_elsewhere = true : silent
30 | csharp_style_var_for_built_in_types = true : silent
31 | csharp_style_var_when_type_is_apparent = true : suggestion
32 | dotnet_style_predefined_type_for_locals_parameters_members = true : suggestion
33 | csharp_style_pattern_local_over_anonymous_function = true : suggestion
34 | dotnet_style_require_accessibility_modifiers = for_non_interface_members : suggestion
35 | csharp_preferred_modifier_order = public,private,internal,protected,static,readonly,async,override : suggestion
36 | csharp_style_pattern_matching_over_as_with_null_check = false : suggestion
37 | dotnet_style_qualification_for_field = false : suggestion
38 | dotnet_style_qualification_for_method = false : suggestion
39 | dotnet_style_qualification_for_property = false : suggestion
40 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | ###############################################################################
2 | # Set default behavior to automatically normalize line endings.
3 | ###############################################################################
4 | * text=auto
5 |
6 | ###############################################################################
7 | # Set default behavior for command prompt diff.
8 | #
9 | # This is need for earlier builds of msysgit that does not have it on by
10 | # default for csharp files.
11 | # Note: This is only used by command line
12 | ###############################################################################
13 | #*.cs diff=csharp
14 |
15 | ###############################################################################
16 | # Set the merge driver for project and solution files
17 | #
18 | # Merging from the command prompt will add diff markers to the files if there
19 | # are conflicts (Merging from VS is not affected by the settings below, in VS
20 | # the diff markers are never inserted). Diff markers may cause the following
21 | # file extensions to fail to load in VS. An alternative would be to treat
22 | # these files as binary and thus will always conflict and require user
23 | # intervention with every merge. To do so, just uncomment the entries below
24 | ###############################################################################
25 | #*.sln merge=binary
26 | #*.csproj merge=binary
27 | #*.vbproj merge=binary
28 | #*.vcxproj merge=binary
29 | #*.vcproj merge=binary
30 | #*.dbproj merge=binary
31 | #*.fsproj merge=binary
32 | #*.lsproj merge=binary
33 | #*.wixproj merge=binary
34 | #*.modelproj merge=binary
35 | #*.sqlproj merge=binary
36 | #*.wwaproj merge=binary
37 |
38 | ###############################################################################
39 | # behavior for image files
40 | #
41 | # image files are treated as binary by default.
42 | ###############################################################################
43 | #*.jpg binary
44 | #*.png binary
45 | #*.gif binary
46 |
47 | ###############################################################################
48 | # diff behavior for common document formats
49 | #
50 | # Convert binary document formats to text before diffing them. This feature
51 | # is only available from the command line. Turn it on by uncommenting the
52 | # entries below.
53 | ###############################################################################
54 | #*.doc diff=astextplain
55 | #*.DOC diff=astextplain
56 | #*.docx diff=astextplain
57 | #*.DOCX diff=astextplain
58 | #*.dot diff=astextplain
59 | #*.DOT diff=astextplain
60 | #*.pdf diff=astextplain
61 | #*.PDF diff=astextplain
62 | #*.rtf diff=astextplain
63 | #*.RTF diff=astextplain
64 |
--------------------------------------------------------------------------------
/.github/workflows/dotnetcore.yml:
--------------------------------------------------------------------------------
1 | name: .NET Core
2 |
3 | on: [push]
4 |
5 | jobs:
6 | build:
7 |
8 | runs-on: ubuntu-latest
9 |
10 | steps:
11 | - uses: actions/checkout@v4
12 | - name: Setup .NET Core
13 | uses: actions/setup-dotnet@v4
14 | with:
15 | dotnet-version: 9.0.x
16 | - name: Tests
17 | run: dotnet test
18 | - name: Pack
19 | run: dotnet pack GenerateAspNetCoreClient -c Release
20 | - name: Upload a Build Artifact
21 | uses: actions/upload-artifact@v4
22 | with:
23 | path: ./**/*.nupkg
24 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
5 |
6 | # User-specific files
7 | *.rsuser
8 | *.suo
9 | *.user
10 | *.userosscache
11 | *.sln.docstates
12 |
13 | # User-specific files (MonoDevelop/Xamarin Studio)
14 | *.userprefs
15 |
16 | # Build results
17 | [Dd]ebug/
18 | [Dd]ebugPublic/
19 | [Rr]elease/
20 | [Rr]eleases/
21 | x64/
22 | x86/
23 | [Aa][Rr][Mm]/
24 | [Aa][Rr][Mm]64/
25 | bld/
26 | [Bb]in/
27 | [Oo]bj/
28 | [Ll]og/
29 |
30 | # Visual Studio 2015/2017 cache/options directory
31 | .vs/
32 | # Uncomment if you have tasks that create the project's static files in wwwroot
33 | #wwwroot/
34 |
35 | # Visual Studio 2017 auto generated files
36 | Generated\ Files/
37 |
38 | # MSTest test Results
39 | [Tt]est[Rr]esult*/
40 | [Bb]uild[Ll]og.*
41 |
42 | # NUNIT
43 | *.VisualState.xml
44 | TestResult.xml
45 |
46 | # Build Results of an ATL Project
47 | [Dd]ebugPS/
48 | [Rr]eleasePS/
49 | dlldata.c
50 |
51 | # Benchmark Results
52 | BenchmarkDotNet.Artifacts/
53 |
54 | # .NET Core
55 | project.lock.json
56 | project.fragment.lock.json
57 | artifacts/
58 |
59 | # StyleCop
60 | StyleCopReport.xml
61 |
62 | # Files built by Visual Studio
63 | *_i.c
64 | *_p.c
65 | *_h.h
66 | *.ilk
67 | *.meta
68 | *.obj
69 | *.iobj
70 | *.pch
71 | *.pdb
72 | *.ipdb
73 | *.pgc
74 | *.pgd
75 | *.rsp
76 | *.sbr
77 | *.tlb
78 | *.tli
79 | *.tlh
80 | *.tmp
81 | *.tmp_proj
82 | *_wpftmp.csproj
83 | *.log
84 | *.vspscc
85 | *.vssscc
86 | .builds
87 | *.pidb
88 | *.svclog
89 | *.scc
90 |
91 | # Chutzpah Test files
92 | _Chutzpah*
93 |
94 | # Visual C++ cache files
95 | ipch/
96 | *.aps
97 | *.ncb
98 | *.opendb
99 | *.opensdf
100 | *.sdf
101 | *.cachefile
102 | *.VC.db
103 | *.VC.VC.opendb
104 |
105 | # Visual Studio profiler
106 | *.psess
107 | *.vsp
108 | *.vspx
109 | *.sap
110 |
111 | # Visual Studio Trace Files
112 | *.e2e
113 |
114 | # TFS 2012 Local Workspace
115 | $tf/
116 |
117 | # Guidance Automation Toolkit
118 | *.gpState
119 |
120 | # ReSharper is a .NET coding add-in
121 | _ReSharper*/
122 | *.[Rr]e[Ss]harper
123 | *.DotSettings.user
124 |
125 | # JustCode is a .NET coding add-in
126 | .JustCode
127 |
128 | # TeamCity is a build add-in
129 | _TeamCity*
130 |
131 | # DotCover is a Code Coverage Tool
132 | *.dotCover
133 |
134 | # AxoCover is a Code Coverage Tool
135 | .axoCover/*
136 | !.axoCover/settings.json
137 |
138 | # Visual Studio code coverage results
139 | *.coverage
140 | *.coveragexml
141 |
142 | # NCrunch
143 | _NCrunch_*
144 | .*crunch*.local.xml
145 | nCrunchTemp_*
146 |
147 | # MightyMoose
148 | *.mm.*
149 | AutoTest.Net/
150 |
151 | # Web workbench (sass)
152 | .sass-cache/
153 |
154 | # Installshield output folder
155 | [Ee]xpress/
156 |
157 | # DocProject is a documentation generator add-in
158 | DocProject/buildhelp/
159 | DocProject/Help/*.HxT
160 | DocProject/Help/*.HxC
161 | DocProject/Help/*.hhc
162 | DocProject/Help/*.hhk
163 | DocProject/Help/*.hhp
164 | DocProject/Help/Html2
165 | DocProject/Help/html
166 |
167 | # Click-Once directory
168 | publish/
169 |
170 | # Publish Web Output
171 | *.[Pp]ublish.xml
172 | *.azurePubxml
173 | # Note: Comment the next line if you want to checkin your web deploy settings,
174 | # but database connection strings (with potential passwords) will be unencrypted
175 | *.pubxml
176 | *.publishproj
177 |
178 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
179 | # checkin your Azure Web App publish settings, but sensitive information contained
180 | # in these scripts will be unencrypted
181 | PublishScripts/
182 |
183 | # NuGet Packages
184 | *.nupkg
185 | # The packages folder can be ignored because of Package Restore
186 | **/[Pp]ackages/*
187 | # except build/, which is used as an MSBuild target.
188 | !**/[Pp]ackages/build/
189 | # Uncomment if necessary however generally it will be regenerated when needed
190 | #!**/[Pp]ackages/repositories.config
191 | # NuGet v3's project.json files produces more ignorable files
192 | *.nuget.props
193 | *.nuget.targets
194 |
195 | # Microsoft Azure Build Output
196 | csx/
197 | *.build.csdef
198 |
199 | # Microsoft Azure Emulator
200 | ecf/
201 | rcf/
202 |
203 | # Windows Store app package directories and files
204 | AppPackages/
205 | BundleArtifacts/
206 | Package.StoreAssociation.xml
207 | _pkginfo.txt
208 | *.appx
209 |
210 | # Visual Studio cache files
211 | # files ending in .cache can be ignored
212 | *.[Cc]ache
213 | # but keep track of directories ending in .cache
214 | !?*.[Cc]ache/
215 |
216 | # Others
217 | ClientBin/
218 | ~$*
219 | *~
220 | *.dbmdl
221 | *.dbproj.schemaview
222 | *.jfm
223 | *.pfx
224 | *.publishsettings
225 | orleans.codegen.cs
226 |
227 | # Including strong name files can present a security risk
228 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
229 | #*.snk
230 |
231 | # Since there are multiple workflows, uncomment next line to ignore bower_components
232 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
233 | #bower_components/
234 |
235 | # RIA/Silverlight projects
236 | Generated_Code/
237 |
238 | # Backup & report files from converting an old project file
239 | # to a newer Visual Studio version. Backup files are not needed,
240 | # because we have git ;-)
241 | _UpgradeReport_Files/
242 | Backup*/
243 | UpgradeLog*.XML
244 | UpgradeLog*.htm
245 | ServiceFabricBackup/
246 | *.rptproj.bak
247 |
248 | # SQL Server files
249 | *.mdf
250 | *.ldf
251 | *.ndf
252 |
253 | # Business Intelligence projects
254 | *.rdl.data
255 | *.bim.layout
256 | *.bim_*.settings
257 | *.rptproj.rsuser
258 | *- Backup*.rdl
259 |
260 | # Microsoft Fakes
261 | FakesAssemblies/
262 |
263 | # GhostDoc plugin setting file
264 | *.GhostDoc.xml
265 |
266 | # Node.js Tools for Visual Studio
267 | .ntvs_analysis.dat
268 | node_modules/
269 |
270 | # Visual Studio 6 build log
271 | *.plg
272 |
273 | # Visual Studio 6 workspace options file
274 | *.opt
275 |
276 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
277 | *.vbw
278 |
279 | # Visual Studio LightSwitch build output
280 | **/*.HTMLClient/GeneratedArtifacts
281 | **/*.DesktopClient/GeneratedArtifacts
282 | **/*.DesktopClient/ModelManifest.xml
283 | **/*.Server/GeneratedArtifacts
284 | **/*.Server/ModelManifest.xml
285 | _Pvt_Extensions
286 |
287 | # Paket dependency manager
288 | .paket/paket.exe
289 | paket-files/
290 |
291 | # FAKE - F# Make
292 | .fake/
293 |
294 | # JetBrains Rider
295 | .idea/
296 | *.sln.iml
297 |
298 | # CodeRush personal settings
299 | .cr/personal
300 |
301 | # Python Tools for Visual Studio (PTVS)
302 | __pycache__/
303 | *.pyc
304 |
305 | # Cake - Uncomment if you are using it
306 | # tools/**
307 | # !tools/packages.config
308 |
309 | # Tabs Studio
310 | *.tss
311 |
312 | # Telerik's JustMock configuration file
313 | *.jmconfig
314 |
315 | # BizTalk build output
316 | *.btp.cs
317 | *.btm.cs
318 | *.odx.cs
319 | *.xsd.cs
320 |
321 | # OpenCover UI analysis results
322 | OpenCover/
323 |
324 | # Azure Stream Analytics local run output
325 | ASALocalRun/
326 |
327 | # MSBuild Binary and Structured Log
328 | *.binlog
329 |
330 | # NVidia Nsight GPU debugger configuration file
331 | *.nvuser
332 |
333 | # MFractors (Xamarin productivity tool) working folder
334 | .mfractor/
335 |
336 | # Local History for Visual Studio
337 | .localhistory/
338 |
339 | # BeatPulse healthcheck temp database
340 | healthchecksdb
341 |
342 | /GenerateAspNetCoreClient/Properties/debug-paths.txt
343 |
344 | *.received.*
--------------------------------------------------------------------------------
/DotNet.Cli.Build/DotNet.Cli.Build.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netstandard2.0
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/DotNet.Cli.Build/Exe.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Diagnostics;
4 | using System.Text;
5 |
6 | namespace DotNet.Cli.Build
7 | {
8 | internal static class Exe
9 | {
10 | public static int Run(
11 | string executable,
12 | IReadOnlyList args,
13 | string workingDirectory = null,
14 | bool interceptOutput = false)
15 | {
16 | var arguments = ToArguments(args);
17 |
18 | Console.WriteLine(executable + " " + arguments);
19 |
20 | var startInfo = new ProcessStartInfo
21 | {
22 | FileName = executable,
23 | Arguments = arguments,
24 | UseShellExecute = false,
25 | RedirectStandardOutput = interceptOutput
26 | };
27 | if (workingDirectory != null)
28 | {
29 | startInfo.WorkingDirectory = workingDirectory;
30 | }
31 |
32 | var process = Process.Start(startInfo);
33 |
34 | if (interceptOutput)
35 | {
36 | string line;
37 | while ((line = process.StandardOutput.ReadLine()) != null)
38 | {
39 | Console.WriteLine(line);
40 | }
41 | }
42 |
43 | process.WaitForExit();
44 |
45 | return process.ExitCode;
46 | }
47 |
48 | private static string ToArguments(IReadOnlyList args)
49 | {
50 | var builder = new StringBuilder();
51 | for (var i = 0; i < args.Count; i++)
52 | {
53 | if (i != 0)
54 | {
55 | builder.Append(" ");
56 | }
57 |
58 | if (args[i].IndexOf(' ') == -1)
59 | {
60 | builder.Append(args[i]);
61 |
62 | continue;
63 | }
64 |
65 | builder.Append("\"");
66 |
67 | var pendingBackslashes = 0;
68 | for (var j = 0; j < args[i].Length; j++)
69 | {
70 | switch (args[i][j])
71 | {
72 | case '\"':
73 | if (pendingBackslashes != 0)
74 | {
75 | builder.Append('\\', pendingBackslashes * 2);
76 | pendingBackslashes = 0;
77 | }
78 |
79 | builder.Append("\\\"");
80 | break;
81 |
82 | case '\\':
83 | pendingBackslashes++;
84 | break;
85 |
86 | default:
87 | if (pendingBackslashes != 0)
88 | {
89 | if (pendingBackslashes == 1)
90 | {
91 | builder.Append("\\");
92 | }
93 | else
94 | {
95 | builder.Append('\\', pendingBackslashes * 2);
96 | }
97 |
98 | pendingBackslashes = 0;
99 | }
100 |
101 | builder.Append(args[i][j]);
102 | break;
103 | }
104 | }
105 |
106 | if (pendingBackslashes != 0)
107 | {
108 | builder.Append('\\', pendingBackslashes * 2);
109 | }
110 |
111 | builder.Append("\"");
112 | }
113 |
114 | return builder.ToString();
115 | }
116 | }
117 | }
--------------------------------------------------------------------------------
/DotNet.Cli.Build/Project.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.IO;
4 | using System.Linq;
5 |
6 | namespace DotNet.Cli.Build
7 | {
8 | public class Project
9 | {
10 | private readonly string _file;
11 | private readonly string _framework;
12 | private readonly string _configuration;
13 | private readonly string _runtime;
14 |
15 | private Project(string file, string framework, string configuration, string runtime)
16 | {
17 | _file = file;
18 | _framework = framework;
19 | _configuration = configuration;
20 | _runtime = runtime;
21 |
22 | ProjectName = Path.GetFileName(file);
23 | }
24 |
25 | public string ProjectName { get; }
26 |
27 | public string AssemblyName { get; set; }
28 | public string Language { get; set; }
29 | public string OutputPath { get; set; }
30 | public string PublishDir { get; set; }
31 | public string PlatformTarget { get; set; }
32 | public string ProjectAssetsFile { get; set; }
33 | public string ProjectDir { get; set; }
34 | public string RootNamespace { get; set; }
35 | public string RuntimeFrameworkVersion { get; set; }
36 | public string TargetFileName { get; set; }
37 | public string TargetFrameworkMoniker { get; set; }
38 |
39 | public string PublishFilePath => Path.Combine(ProjectDir, PublishDir, TargetFileName);
40 | public string OutputFilePath => Path.Combine(ProjectDir, OutputPath, TargetFileName);
41 |
42 | public static Project FromPath(
43 | string path,
44 | string buildExtensionsDir = null,
45 | string framework = null,
46 | string configuration = null,
47 | string runtime = null)
48 | {
49 | var file = GetProjectFilePath(path);
50 |
51 | if (buildExtensionsDir == null)
52 | {
53 | buildExtensionsDir = Path.Combine(Path.GetDirectoryName(file), "obj");
54 | }
55 |
56 | Directory.CreateDirectory(buildExtensionsDir);
57 |
58 | var dotnetCliTargetsPath = Path.Combine(
59 | buildExtensionsDir,
60 | Path.GetFileName(file) + ".DotNetCliBuild.targets");
61 | using (var input = typeof(Project).Assembly.GetManifestResourceStream(
62 | "DotNet.Cli.Build.Resources.DotNetCliBuild.targets"))
63 |
64 | using (var output = File.OpenWrite(dotnetCliTargetsPath))
65 | {
66 | input.CopyTo(output);
67 | }
68 |
69 | IDictionary metadata;
70 | var metadataFile = Path.GetTempFileName();
71 | try
72 | {
73 | var propertyArg = "/property:DotNetCliBuildMetadataFile=" + metadataFile;
74 | if (framework != null)
75 | {
76 | propertyArg += ";TargetFramework=" + framework;
77 | }
78 |
79 | if (configuration != null)
80 | {
81 | propertyArg += ";Configuration=" + configuration;
82 | }
83 |
84 | if (runtime != null)
85 | {
86 | propertyArg += ";RuntimeIdentifier=" + runtime;
87 | }
88 |
89 | var args = new List
90 | {
91 | "msbuild",
92 | "/target:__GetProjectMetadata",
93 | propertyArg,
94 | "/verbosity:quiet",
95 | "/nologo"
96 | };
97 |
98 | if (file != null)
99 | {
100 | args.Add(file);
101 | }
102 |
103 | var exitCode = Exe.Run("dotnet", args);
104 | if (exitCode != 0)
105 | {
106 | throw new Exception("Unable to retrieve project metadata.");
107 | }
108 |
109 | metadata = File.ReadLines(metadataFile)
110 | .Select(l => l.Split(new[] { ':' }, 2))
111 | .ToDictionary(s => s[0], s => s[1].TrimStart());
112 | }
113 | finally
114 | {
115 | File.Delete(metadataFile);
116 | }
117 |
118 | var platformTarget = metadata["PlatformTarget"];
119 | if (platformTarget.Length == 0)
120 | {
121 | platformTarget = metadata["Platform"];
122 | }
123 |
124 | return new Project(file, framework, configuration, runtime)
125 | {
126 | AssemblyName = metadata["AssemblyName"],
127 | Language = metadata["Language"],
128 | OutputPath = metadata["OutputPath"],
129 | PublishDir = metadata["PublishDir"],
130 | PlatformTarget = platformTarget,
131 | ProjectAssetsFile = metadata["ProjectAssetsFile"],
132 | ProjectDir = metadata["ProjectDir"],
133 | RootNamespace = metadata["RootNamespace"],
134 | RuntimeFrameworkVersion = metadata["RuntimeFrameworkVersion"],
135 | TargetFileName = metadata["TargetFileName"],
136 | TargetFrameworkMoniker = metadata["TargetFrameworkMoniker"]
137 | };
138 | }
139 |
140 | public void Build()
141 | {
142 | var args = new List { "build" };
143 |
144 | if (_file != null)
145 | {
146 | args.Add(_file);
147 | }
148 |
149 | if (_framework != null)
150 | {
151 | args.Add("--framework");
152 | args.Add(_framework);
153 | }
154 |
155 | if (_configuration != null)
156 | {
157 | args.Add("--configuration");
158 | args.Add(_configuration);
159 | }
160 |
161 | if (_runtime != null)
162 | {
163 | args.Add("--runtime");
164 | args.Add(_runtime);
165 | }
166 |
167 | args.Add("/verbosity:quiet");
168 | args.Add("/nologo");
169 |
170 | var exitCode = Exe.Run("dotnet", args, interceptOutput: true);
171 | if (exitCode != 0)
172 | {
173 | throw new Exception("BuildFailed");
174 | }
175 | }
176 |
177 | public void Publish()
178 | {
179 | var args = new List { "publish" };
180 |
181 | if (_file != null)
182 | {
183 | args.Add(_file);
184 | }
185 |
186 | if (_framework != null)
187 | {
188 | args.Add("--framework");
189 | args.Add(_framework);
190 | }
191 |
192 | if (_configuration != null)
193 | {
194 | args.Add("--configuration");
195 | args.Add(_configuration);
196 | }
197 |
198 | if (_runtime != null)
199 | {
200 | args.Add("--runtime");
201 | args.Add(_runtime);
202 | }
203 |
204 | args.Add("/verbosity:quiet");
205 | args.Add("/nologo");
206 |
207 | var exitCode = Exe.Run("dotnet", args, interceptOutput: true);
208 | if (exitCode != 0)
209 | {
210 | throw new Exception("PublishFailed");
211 | }
212 | }
213 |
214 | private static string GetProjectFilePath(string path)
215 | {
216 | if (string.IsNullOrEmpty(path))
217 | throw new ArgumentNullException(nameof(path));
218 |
219 | if (File.Exists(path))
220 | {
221 | // If path is file - return as is
222 | return path;
223 | }
224 | else if (Directory.Exists(path))
225 | {
226 | // If path is directory - try finding csproj file
227 | var csprojFiles = Directory.GetFiles(path, "*.csproj");
228 |
229 | if (csprojFiles.Length == 0)
230 | throw new ArgumentException("No project files found");
231 |
232 | if (csprojFiles.Length > 1)
233 | throw new ArgumentException("Multiple project files found");
234 |
235 | return csprojFiles[0];
236 | }
237 | else
238 | {
239 | throw new ArgumentException("Specified path does not exist");
240 | }
241 | }
242 | }
243 | }
244 |
--------------------------------------------------------------------------------
/DotNet.Cli.Build/Resources/DotNetCliBuild.targets:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/GenerateAspNetCoreClient.Command/ClientModelBuilder.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.IO;
4 | using System.Linq;
5 | using System.Net.Http;
6 | using System.Reflection;
7 | using System.Threading;
8 | using GenerateAspNetCoreClient.Command.Extensions;
9 | using GenerateAspNetCoreClient.Command.Model;
10 | using GenerateAspNetCoreClient.Options;
11 | using Microsoft.AspNetCore.Http;
12 | using Microsoft.AspNetCore.Mvc;
13 | using Microsoft.AspNetCore.Mvc.ApiExplorer;
14 | using Microsoft.AspNetCore.Mvc.Controllers;
15 | using Microsoft.AspNetCore.Mvc.ModelBinding;
16 | using Microsoft.AspNetCore.Routing;
17 | using Namotion.Reflection;
18 |
19 | namespace GenerateAspNetCoreClient.Command
20 | {
21 | public class ClientModelBuilder
22 | {
23 | private readonly ApiDescriptionGroupCollection apiExplorer;
24 | private readonly GenerateClientOptions options;
25 | private readonly Assembly webProjectAssembly;
26 |
27 | public ClientModelBuilder(
28 | ApiDescriptionGroupCollection apiExplorer,
29 | GenerateClientOptions options,
30 | Assembly webProjectAssembly)
31 | {
32 | this.apiExplorer = apiExplorer;
33 | this.options = options;
34 | this.webProjectAssembly = webProjectAssembly;
35 | }
36 |
37 | public List GetClientCollection()
38 | {
39 | var apiDescriptions = apiExplorer.Items
40 | .SelectMany(i => i.Items)
41 | .ToList();
42 |
43 | FilterDescriptions(apiDescriptions);
44 |
45 | var assemblyName = webProjectAssembly.GetName().Name;
46 | var apiGroupsDescriptions = apiDescriptions.GroupBy(i => GroupInfo.From(i, assemblyName));
47 |
48 | string commonControllerNamespacePart = GetCommonNamespacesPart(apiGroupsDescriptions);
49 |
50 | var clients = apiGroupsDescriptions.Select(apis =>
51 | GetClientModel(
52 | commonControllerNamespace: commonControllerNamespacePart,
53 | controllerInfo: apis.Key,
54 | apiDescriptions: apis.ToList())
55 | ).ToList();
56 |
57 | return clients;
58 | }
59 |
60 | private void FilterDescriptions(List apiDescriptions)
61 | {
62 | if (!string.IsNullOrEmpty(options.ExcludeTypes))
63 | {
64 | apiDescriptions.RemoveAll(api => api.ActionDescriptor is ControllerActionDescriptor controllerActionDescriptor
65 | && controllerActionDescriptor.ControllerTypeInfo.FullName?.Contains(options.ExcludeTypes) == true);
66 | }
67 |
68 | if (!string.IsNullOrEmpty(options.IncludeTypes))
69 | {
70 | apiDescriptions.RemoveAll(api => api.ActionDescriptor is ControllerActionDescriptor controllerActionDescriptor
71 | && controllerActionDescriptor.ControllerTypeInfo.FullName?.Contains(options.IncludeTypes) != true);
72 | }
73 |
74 | if (!string.IsNullOrEmpty(options.ExcludePaths))
75 | {
76 | apiDescriptions.RemoveAll(api => ("/" + api.RelativePath).Contains(options.ExcludePaths));
77 | }
78 |
79 | if (!string.IsNullOrEmpty(options.IncludePaths))
80 | {
81 | apiDescriptions.RemoveAll(api => !("/" + api.RelativePath).Contains(options.IncludePaths));
82 | }
83 | }
84 |
85 | internal Client GetClientModel(
86 | string commonControllerNamespace,
87 | GroupInfo controllerInfo,
88 | List apiDescriptions)
89 | {
90 | apiDescriptions = HandleDuplicates(apiDescriptions);
91 |
92 | var subPath = GetSubPath(controllerInfo, commonControllerNamespace);
93 |
94 | var groupNamePascalCase = controllerInfo.GroupName.ToPascalCase();
95 | var name = options.TypeNamePattern
96 | .Replace("[controller]", groupNamePascalCase)
97 | .Replace("[group]", groupNamePascalCase);
98 |
99 | var clientNamespace = string.Join(".", new[] { options.Namespace }.Concat(subPath));
100 |
101 | var methods = apiDescriptions.Select(GetEndpointMethod).ToList();
102 |
103 | return new Client
104 | (
105 | location: Path.Combine(subPath),
106 | @namespace: clientNamespace,
107 | accessModifier: options.AccessModifier,
108 | name: name,
109 | endpointMethods: methods
110 | );
111 | }
112 |
113 | internal EndpointMethod GetEndpointMethod(ApiDescription apiDescription)
114 | {
115 | var responseType = GetResponseType(apiDescription);
116 |
117 | if (responseType == null)
118 | {
119 | Console.WriteLine($"Cannot find return type for " + apiDescription.ActionDescriptor.DisplayName);
120 | responseType = typeof(void);
121 | }
122 |
123 | return new EndpointMethod
124 | (
125 | xmlDoc: GetXmlDoc(apiDescription),
126 | httpMethod: new HttpMethod(apiDescription.HttpMethod ?? HttpMethod.Get.Method),
127 | path: apiDescription.RelativePath?.TrimEnd('/') ?? "",
128 | responseType: responseType,
129 | name: GetActionName(apiDescription),
130 | parameters: GetParameters(apiDescription)
131 | );
132 | }
133 |
134 | private string GetActionName(ApiDescription apiDescription)
135 | {
136 | if (apiDescription.ActionDescriptor.EndpointMetadata.OfType().FirstOrDefault()?.RouteName is string routeName)
137 | return routeName;
138 |
139 | if (apiDescription.ActionDescriptor is ControllerActionDescriptor { ActionName: string actionName })
140 | return actionName;
141 |
142 | var method = apiDescription.HttpMethod ?? "GET";
143 | return (method + " " + apiDescription.RelativePath).ToPascalCase();
144 | }
145 |
146 | private List GetParameters(ApiDescription apiDescription)
147 | {
148 | var parametersList = new List();
149 |
150 | for (int i = 0; i < apiDescription.ParameterDescriptions.Count; i++)
151 | {
152 | var parameterDescription = apiDescription.ParameterDescriptions[i];
153 | var paramType = parameterDescription.ParameterDescriptor?.ParameterType;
154 |
155 | if (paramType == typeof(CancellationToken))
156 | continue;
157 |
158 | // IFormFile
159 | if (paramType == typeof(IFormFile))
160 | {
161 | var name = parameterDescription.ParameterDescriptor.Name;
162 |
163 | parametersList.Add(new Parameter(
164 | source: ParameterSource.File,
165 | type: typeof(Stream),
166 | name: parameterDescription.Name,
167 | parameterName: name.ToCamelCase(),
168 | defaultValueLiteral: null));
169 |
170 | // Skip parameters that correspond to same file
171 | while (i + 1 < apiDescription.ParameterDescriptions.Count
172 | && apiDescription.ParameterDescriptions[i + 1].ParameterDescriptor?.ParameterType == typeof(IFormFile)
173 | && apiDescription.ParameterDescriptions[i + 1].ParameterDescriptor?.Name == name)
174 | {
175 | i++;
176 | }
177 |
178 | continue;
179 | }
180 |
181 | // IEnumerable
182 | if (paramType != null)
183 | {
184 | if (typeof(IEnumerable).IsAssignableFrom(paramType))
185 | {
186 | var name = parameterDescription.ParameterDescriptor?.Name;
187 |
188 | parametersList.Add(new Parameter(
189 | source: ParameterSource.File,
190 | type: typeof(List),
191 | name: parameterDescription.Name,
192 | parameterName: name?.ToCamelCase() ?? "files",
193 | defaultValueLiteral: null));
194 |
195 | continue;
196 | }
197 | }
198 |
199 | // Form
200 | // API explorer shows form as separate parameters. We want to have single model parameter.
201 | if (parameterDescription.Source == BindingSource.Form)
202 | {
203 | var name = parameterDescription.ParameterDescriptor?.Name ?? "form";
204 | var formType = paramType ?? typeof(object);
205 |
206 | if (formType == typeof(IFormCollection))
207 | {
208 | parametersList.Add(new Parameter(
209 | source: ParameterSource.Form,
210 | type: typeof(Dictionary),
211 | name: parameterDescription.Name,
212 | parameterName: name.ToCamelCase(),
213 | defaultValueLiteral: null));
214 |
215 | continue;
216 | }
217 | else
218 | {
219 | var sameFormParameters = apiDescription.ParameterDescriptions.Skip(i - 1)
220 | .TakeWhile(d => d.ParameterDescriptor?.ParameterType == formType && d.ParameterDescriptor?.Name == name)
221 | .ToArray();
222 |
223 | // If form model has file parameters - we have to put it as separate parameters.
224 | if (sameFormParameters.All(p => p.Source.Id != "FormFile"))
225 | {
226 | parametersList.Add(new Parameter(
227 | source: ParameterSource.Form,
228 | type: formType,
229 | name: parameterDescription.Name,
230 | parameterName: name.ToCamelCase(),
231 | defaultValueLiteral: "null"));
232 |
233 | if (sameFormParameters.Length > 0)
234 | i += sameFormParameters.Length - 1;
235 |
236 | continue;
237 | }
238 | }
239 | }
240 |
241 | if (options.UseQueryModels
242 | && parameterDescription.Source == BindingSource.Query
243 | && parameterDescription.ModelMetadata?.ContainerType != null
244 | && parameterDescription.ParameterDescriptor != null)
245 | {
246 | var name = parameterDescription.ParameterDescriptor.Name;
247 | var containerType = parameterDescription.ModelMetadata.ContainerType;
248 |
249 | parametersList.Add(new Parameter(
250 | source: ParameterSource.Query,
251 | type: containerType,
252 | name: parameterDescription.Name,
253 | parameterName: name.ToCamelCase(),
254 | defaultValueLiteral: "null"));
255 |
256 | // Skip parameters that correspond to same query model
257 | while (i + 1 < apiDescription.ParameterDescriptions.Count
258 | && apiDescription.ParameterDescriptions[i + 1].ModelMetadata?.ContainerType == containerType
259 | && apiDescription.ParameterDescriptions[i + 1].ParameterDescriptor?.Name == name)
260 | {
261 | i++;
262 | }
263 |
264 | continue;
265 | }
266 |
267 | if (parametersList.Any(p => p.Name.Equals(parameterDescription.Name, StringComparison.OrdinalIgnoreCase)))
268 | {
269 | Console.WriteLine($"Duplicate parameter '{parameterDescription.Name}' for '{apiDescription.ActionDescriptor.DisplayName}'");
270 | continue;
271 | }
272 |
273 | var source = parameterDescription.Source.Id switch
274 | {
275 | "Body" => ParameterSource.Body,
276 | "Path" => ParameterSource.Path,
277 | "FormFile" => ParameterSource.File,
278 | "Query" => ParameterSource.Query,
279 | "Header" => ParameterSource.Header,
280 | "Form" => ParameterSource.Form,
281 | _ => ParameterSource.Query
282 | };
283 |
284 | // Is it possible to have other static values, apart from headers?
285 | var isStaticValue = parameterDescription.Source == BindingSource.Header && parameterDescription.BindingInfo is null;
286 |
287 | var isQueryModel = source is ParameterSource.Query or ParameterSource.Form
288 | && parameterDescription.Type != parameterDescription.ParameterDescriptor?.ParameterType;
289 |
290 | // If query model - use parameterDescription.Name, as ParameterDescriptor.Name is name for the whole model,
291 | // not separate parameters.
292 | var parameterName = isQueryModel
293 | ? parameterDescription.Name.ToCamelCase()
294 | : (parameterDescription.ParameterDescriptor?.Name ?? parameterDescription.Name).ToCamelCase();
295 |
296 | parameterName = new string(parameterName.Where(char.IsLetterOrDigit).ToArray());
297 |
298 | Type type;
299 | if (parameterDescription.Source == BindingSource.FormFile)
300 | {
301 | type = typeof(IEnumerable).IsAssignableFrom(parameterDescription.Type)
302 | ? typeof(List)
303 | : typeof(Stream);
304 | }
305 | else
306 | {
307 | type = parameterDescription.ModelMetadata?.ModelType ?? parameterDescription.Type;
308 | }
309 |
310 | var defaultValue = GetDefaultValueLiteral(parameterDescription, type);
311 |
312 | if (defaultValue == "null")
313 | {
314 | type = type.ToNullable();
315 | }
316 |
317 | parametersList.Add(new Parameter(
318 | source: source,
319 | type: type,
320 | name: parameterDescription.Name,
321 | parameterName: parameterName,
322 | defaultValueLiteral: defaultValue,
323 | isStaticValue: isStaticValue));
324 | }
325 |
326 | if (options.AddCancellationTokenParameters)
327 | {
328 | parametersList.Add(new Parameter(
329 | source: ParameterSource.Other,
330 | type: typeof(CancellationToken),
331 | name: "cancellationToken",
332 | parameterName: "cancellationToken",
333 | defaultValueLiteral: "default"));
334 | }
335 |
336 | return parametersList;
337 | }
338 |
339 | private static string? GetXmlDoc(ApiDescription apiDescription)
340 | {
341 | var xmlElement = (apiDescription.ActionDescriptor as ControllerActionDescriptor)?.MethodInfo.GetXmlDocsElement();
342 |
343 | if (xmlElement == null)
344 | return null;
345 |
346 | var xmlLines = xmlElement.Elements()
347 | .Select(e => e.ToString())
348 | .SelectMany(s => s.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries))
349 | .Select(line => line.Trim().Replace("cref=\"T:", "cref=\""));
350 |
351 | var xmlDoc = string.Join(Environment.NewLine, xmlLines).Indent("/// ");
352 |
353 | return xmlDoc;
354 | }
355 |
356 | private static Type? GetResponseType(ApiDescription apiDescription)
357 | {
358 | var responseType = apiDescription.SupportedResponseTypes
359 | .OrderBy(r => r.StatusCode)
360 | .FirstOrDefault(r => r.StatusCode >= 200 && r.StatusCode < 300)
361 | ?.Type;
362 |
363 | if (responseType is null)
364 | {
365 | // Workaround for bug https://github.com/dotnet/aspnetcore/issues/30465
366 | var methodInfo = (apiDescription.ActionDescriptor as ControllerActionDescriptor)?.MethodInfo;
367 | var methodResponseType = methodInfo?.ReturnType?.UnwrapTask();
368 |
369 | if (methodResponseType?.IsAssignableTo(typeof(FileResult)) == true)
370 | {
371 | responseType = typeof(Stream);
372 | }
373 | }
374 |
375 | return responseType;
376 | }
377 |
378 | private static string GetCommonNamespacesPart(IEnumerable> controllerApiDescriptions)
379 | {
380 | var namespaces = controllerApiDescriptions
381 | .Select(c => c.Key)
382 | .Select(c => c.Namespace ?? "");
383 |
384 | return namespaces.GetCommonPart(".");
385 | }
386 |
387 | private static string? GetDefaultValueLiteral(ApiParameterDescription parameter, Type parameterType)
388 | {
389 | var defaultValue = parameter.DefaultValue;
390 |
391 | if (defaultValue != null && defaultValue is not DBNull)
392 | {
393 | // If defaultValue is not null - return it.
394 | return defaultValue.ToLiteral();
395 | }
396 |
397 | var isRequired = parameter.IsRequired;
398 | isRequired |= parameter.ModelMetadata?.IsBindingRequired == true;
399 |
400 | if (!parameterType.IsValueType || parameterType.IsNullable())
401 | {
402 | isRequired |= parameter.ModelMetadata?.IsRequired == true;
403 | }
404 |
405 | if (isRequired == false)
406 | {
407 | // If defaultValue is null, but value is not required - return it anyway.
408 | return "null";
409 | }
410 |
411 | return null;
412 | }
413 |
414 | private static string[] GetSubPath(GroupInfo controllerActionDescriptor, string commonNamespace)
415 | {
416 | return (controllerActionDescriptor.Namespace ?? "")
417 | .Substring(commonNamespace.Length)
418 | .Split(".")
419 | .Select(nsPart => nsPart.Replace("Controllers", ""))
420 | .Where(nsPart => nsPart != "")
421 | .ToArray();
422 | }
423 |
424 | private static List HandleDuplicates(List apiDescriptions)
425 | {
426 | var conflictingApisGroups = apiDescriptions
427 | .Where(api => api.ActionDescriptor is ControllerActionDescriptor)
428 | .GroupBy(api => ((ControllerActionDescriptor)api.ActionDescriptor).ActionName
429 | + string.Concat(api.ParameterDescriptions.Select(p => p.Type?.FullName ?? "-")))
430 | .Where(g => g.Count() > 1);
431 |
432 | foreach (var conflictingApis in conflictingApisGroups)
433 | {
434 | // Take suffixes from path
435 | var commonPathPart = conflictingApis.Select(api => api.RelativePath ?? "").GetCommonPart("/");
436 |
437 | foreach (var api in conflictingApis)
438 | {
439 | var suffix = api.RelativePath is null || api.RelativePath == commonPathPart
440 | ? ""
441 | : api.RelativePath[(commonPathPart.Length + 1)..].ToPascalCase();
442 |
443 | ((ControllerActionDescriptor)api.ActionDescriptor).ActionName += suffix;
444 | }
445 | }
446 |
447 | return apiDescriptions;
448 | }
449 | }
450 | }
451 |
--------------------------------------------------------------------------------
/GenerateAspNetCoreClient.Command/Extensions/ObjectExtensions.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace GenerateAspNetCoreClient.Command.Extensions
4 | {
5 | internal static class ObjectExtensions
6 | {
7 | public static string ToLiteral(this object? obj)
8 | {
9 | if (obj == null)
10 | return "null";
11 |
12 | var type = obj.GetType();
13 |
14 | return obj switch
15 | {
16 | string s => '"' + s + '"',
17 | char c => "'" + c + "'",
18 | bool b => b ? "true" : "false",
19 | _ when type.IsEnum && Enum.IsDefined(type, obj) => $"{type.Name}.{obj}",
20 | _ when type.IsPrimitive => obj.ToString() ?? "",
21 | _ => throw new NotSupportedException()
22 | };
23 | }
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/GenerateAspNetCoreClient.Command/Extensions/StringExtensions.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text.RegularExpressions;
5 |
6 | namespace GenerateAspNetCoreClient.Command.Extensions
7 | {
8 | internal static class StringExtensions
9 | {
10 | private static readonly Regex NonAlphaNumericRegex = new Regex(@"[^a-zA-Z0-9]+");
11 |
12 | public static string ToCamelCase(this string @this)
13 | {
14 | if (@this.Length == 0)
15 | return @this;
16 |
17 | return char.ToLowerInvariant(@this[0]) + @this.Substring(1);
18 | }
19 |
20 | public static string ToPascalCase(this string @this)
21 | {
22 | if (@this.Length == 0)
23 | return @this;
24 |
25 | var parts = NonAlphaNumericRegex
26 | .Split(@this)
27 | .Select(PartToPascalCase);
28 |
29 | return string.Concat(parts);
30 |
31 | static string PartToPascalCase(string part)
32 | {
33 | if (part.Length == 0)
34 | return part;
35 |
36 | if (part.ToUpperInvariant() == part)
37 | {
38 | // If part is all uppercase - convert to lowercase all apart from first letter.
39 | return part[0] + part.Substring(1).ToLowerInvariant();
40 | }
41 | else
42 | {
43 | // Otherwise - convert first letter to uppercase, everything else - as is.
44 | return char.ToUpperInvariant(part[0]) + part.Substring(1);
45 | }
46 | }
47 | }
48 |
49 | public static string Indent(this string @this, string indent)
50 | {
51 | var lines = @this.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None);
52 | var indentedLines = lines.Select(line => line.Length == 0 ? line : indent + line);
53 | return string.Join(Environment.NewLine, indentedLines);
54 | }
55 |
56 | public static string GetCommonPart(this IEnumerable @this, string partSeparator)
57 | {
58 | string[][] partsArrays = @this
59 | .Select(ns => ns.Split(partSeparator))
60 | .ToArray();
61 |
62 | if (partsArrays.Length == 0)
63 | return "";
64 |
65 | var anyParts = partsArrays[0];
66 | var commonParts = anyParts.TakeWhile((part, i) => partsArrays.All(ns => ns.Length > i && ns[i] == part));
67 |
68 | return string.Join(partSeparator, commonParts);
69 | }
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/GenerateAspNetCoreClient.Command/Extensions/TypeExtensions.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Threading.Tasks;
5 |
6 | namespace GenerateAspNetCoreClient.Command.Extensions
7 | {
8 | internal static class TypeExtensions
9 | {
10 | private static readonly Dictionary DefaultTypes = new Dictionary
11 | {
12 | [typeof(void)] = "void",
13 | [typeof(object)] = "object",
14 | [typeof(sbyte)] = "sbyte",
15 | [typeof(byte)] = "byte",
16 | [typeof(short)] = "short",
17 | [typeof(ushort)] = "ushort",
18 | [typeof(int)] = "int",
19 | [typeof(uint)] = "uint",
20 | [typeof(long)] = "long",
21 | [typeof(ulong)] = "ulong",
22 | [typeof(decimal)] = "decimal",
23 | [typeof(float)] = "float",
24 | [typeof(double)] = "double",
25 | [typeof(bool)] = "bool",
26 | [typeof(char)] = "char",
27 | [typeof(string)] = "string"
28 | };
29 |
30 | public static bool IsBuiltInType(this Type @this)
31 | {
32 | if (DefaultTypes.ContainsKey(@this))
33 | return true;
34 |
35 | if (@this.IsGenericType
36 | && @this.GetGenericTypeDefinition() == typeof(Nullable<>)
37 | && DefaultTypes.ContainsKey(@this.GetGenericArguments()[0]))
38 | {
39 | return true;
40 | }
41 |
42 | if (@this.IsArray && DefaultTypes.ContainsKey(@this.GetElementType()!))
43 | return true;
44 |
45 | return false;
46 | }
47 |
48 | public static string GetName(this Type @this, HashSet ambiguousTypes)
49 | {
50 | if (@this.IsGenericType && @this.GetGenericTypeDefinition() == typeof(Nullable<>))
51 | {
52 | var underlyingType = @this.GenericTypeArguments[0];
53 | return underlyingType.GetName(ambiguousTypes) + "?";
54 | }
55 |
56 | if (@this.IsArray)
57 | {
58 | var elementType = @this.GetElementType();
59 |
60 | if (elementType != null)
61 | {
62 | return elementType.GetName(ambiguousTypes) + "[]";
63 | }
64 | }
65 |
66 | if (!DefaultTypes.TryGetValue(@this, out var name))
67 | name = @this.Name;
68 |
69 | if (ambiguousTypes.Contains(@this))
70 | {
71 | name = @this.Namespace + "." + name;
72 | }
73 |
74 | if (@this.IsConstructedGenericType)
75 | {
76 | name = name.Substring(0, name.LastIndexOf('`'));
77 |
78 | var genericNames = @this.GetGenericArguments().Select(a => a.GetName(ambiguousTypes));
79 |
80 | name += $"<{string.Join(", ", genericNames)}>";
81 | }
82 |
83 | return name;
84 | }
85 |
86 | public static Type WrapInTask(this Type @this)
87 | {
88 | if (@this == typeof(void))
89 | return typeof(Task);
90 |
91 | return typeof(Task<>).MakeGenericType(@this);
92 | }
93 |
94 | public static Type UnwrapTask(this Type @this)
95 | {
96 | return @this.IsGenericType && @this.GetGenericTypeDefinition() == typeof(Task<>)
97 | ? @this.GetGenericArguments()[0]
98 | : @this;
99 | }
100 |
101 | public static Type ToNullable(this Type @this)
102 | {
103 | if (!@this.IsValueType)
104 | return @this;
105 |
106 | if (IsNullable(@this))
107 | return @this;
108 |
109 | return typeof(Nullable<>).MakeGenericType(@this);
110 | }
111 |
112 | public static bool IsNullable(this Type @this)
113 | {
114 | return @this.IsGenericType && @this.GetGenericTypeDefinition() == typeof(Nullable<>);
115 | }
116 | }
117 | }
118 |
--------------------------------------------------------------------------------
/GenerateAspNetCoreClient.Command/GenerateAspNetCoreClient.Command.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net9.0
5 | enable
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/GenerateAspNetCoreClient.Command/GenerateClientCommand.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections;
3 | using System.Collections.Generic;
4 | using System.IO;
5 | using System.Linq;
6 | using System.Reflection;
7 | using GenerateAspNetCoreClient.Command.Extensions;
8 | using GenerateAspNetCoreClient.Command.Model;
9 | using GenerateAspNetCoreClient.Options;
10 | using Microsoft.AspNetCore.Mvc.ApiExplorer;
11 | using Microsoft.Extensions.DependencyInjection;
12 |
13 | namespace GenerateAspNetCoreClient.Command
14 | {
15 | public class GenerateClientCommand
16 | {
17 | public static void Invoke(Assembly assembly, GenerateClientOptions options)
18 | {
19 | options.AdditionalNamespaces = ["System.Threading.Tasks", "Refit"];
20 | var apiExplorer = GetApiExplorer(assembly, options.Environment);
21 | var clientModelBuilder = new ClientModelBuilder(apiExplorer, options, assembly);
22 | var clientCollection = clientModelBuilder.GetClientCollection();
23 |
24 | var ambiguousTypes = GetAmbiguousTypes(clientCollection);
25 |
26 | foreach (var clientModel in clientCollection)
27 | {
28 | var clientText = CreateClient(clientModel, ambiguousTypes, options);
29 |
30 | var path = Path.Combine(options.OutPath, clientModel.Location);
31 | Directory.CreateDirectory(path);
32 |
33 | File.WriteAllText(Path.Combine(path, $"{clientModel.Name}.cs"), clientText);
34 | }
35 | }
36 |
37 | private static ApiDescriptionGroupCollection GetApiExplorer(Assembly assembly, string? environment)
38 | {
39 | using var _ = new RunSettings(Path.GetDirectoryName(assembly.Location)!, environment);
40 |
41 | var services = ServiceProviderResolver.GetServiceProvider(assembly);
42 | var apiExplorerProvider = services.GetRequiredService();
43 |
44 | return apiExplorerProvider.ApiDescriptionGroups;
45 | }
46 |
47 | private static string CreateClient(Client clientModel, HashSet ambiguousTypes, GenerateClientOptions options)
48 | {
49 | IEnumerable endpointMethods = clientModel.EndpointMethods;
50 | endpointMethods = HandleEndpointDuplicates(endpointMethods, ambiguousTypes);
51 | endpointMethods = HandleSignatureDuplicates(endpointMethods, ambiguousTypes);
52 | var namespaces = GetImportedNamespaces(clientModel, ambiguousTypes, options);
53 |
54 | var methodDescriptions = endpointMethods.Select(endpointMethod =>
55 | {
56 | var xmlDoc = endpointMethod.XmlDoc;
57 |
58 | if (!string.IsNullOrEmpty(xmlDoc))
59 | xmlDoc += Environment.NewLine;
60 |
61 | var multipartAttribute = endpointMethod.IsMultipart
62 | ? "[Multipart]" + Environment.NewLine
63 | : "";
64 |
65 | var staticHeaders = endpointMethod.Parameters.Where(p => p.Source == ParameterSource.Header && p.IsConstant).ToArray();
66 | var staticHeadersAttribute = staticHeaders.Length > 0
67 | ? $"[Headers({string.Join(", ", staticHeaders.Select(h => $"\"{h.Name}: {h.DefaultValueLiteral!.Trim('"')}\""))})]" + Environment.NewLine
68 | : "";
69 |
70 | var parameterStrings = endpointMethod.Parameters
71 | .Except(staticHeaders)
72 | .OrderBy(p => p.DefaultValueLiteral != null)
73 | .Select(p =>
74 | {
75 | var attribute = p.Source switch
76 | {
77 | ParameterSource.Body => "[Body] ",
78 | ParameterSource.Form when !endpointMethod.IsMultipart => "[Body(BodySerializationMethod.UrlEncoded)] ",
79 | ParameterSource.Header => $"[Header(\"{p.Name}\")] ",
80 | ParameterSource.Query => GetQueryAttribute(p),
81 | _ => ""
82 | };
83 |
84 | string type;
85 | if (p.Source == ParameterSource.File)
86 | {
87 | bool isEnumerable = p.Type != typeof(string) && typeof(IEnumerable).IsAssignableFrom(p.Type);
88 | type = isEnumerable ? "List" : "MultipartItem";
89 | }
90 | else
91 | {
92 | type = p.Type.GetName(ambiguousTypes);
93 | }
94 |
95 | var defaultValue = p.DefaultValueLiteral == null ? "" : " = " + p.DefaultValueLiteral;
96 | return $"{attribute}{type} {p.ParameterName}{defaultValue}";
97 | })
98 | .ToArray();
99 |
100 | var httpMethodAttribute = endpointMethod.HttpMethod.ToString().ToPascalCase();
101 | var methodPathAttribute = $@"[{httpMethodAttribute}(""/{endpointMethod.Path}"")]";
102 |
103 | var responseTypeName = GetResponseTypeName(endpointMethod.ResponseType, ambiguousTypes, options);
104 |
105 | return
106 | $@"{xmlDoc}{multipartAttribute}{staticHeadersAttribute}{methodPathAttribute}
107 | {responseTypeName} {endpointMethod.Name}({string.Join(", ", parameterStrings)});";
108 | }).ToArray();
109 |
110 | return
111 | $@"//
112 |
113 | {string.Join(Environment.NewLine, namespaces.Select(n => $"using {n};"))}
114 |
115 | namespace {clientModel.Namespace}
116 | {{
117 | {clientModel.AccessModifier} partial interface {clientModel.Name}
118 | {{
119 | {string.Join(Environment.NewLine + Environment.NewLine, methodDescriptions).Indent(" ")}
120 | }}
121 | }}";
122 | }
123 |
124 | private static IEnumerable GetImportedNamespaces(Client clientModel, HashSet ambiguousTypes, GenerateClientOptions options)
125 | {
126 | var namespaces = GetNamespaces(clientModel.EndpointMethods, ambiguousTypes)
127 | .Concat(options.AdditionalNamespaces);
128 |
129 | namespaces = namespaces
130 | .OrderByDescending(ns => ns.StartsWith("System"))
131 | .ThenBy(ns => ns);
132 |
133 | return namespaces;
134 | }
135 |
136 | private static string GetResponseTypeName(Type responseType, HashSet ambiguousTypes, GenerateClientOptions options)
137 | {
138 | if (options.UseApiResponses)
139 | {
140 | return responseType == typeof(void)
141 | ? "Task"
142 | : $"Task>";
143 | }
144 | else
145 | {
146 | return responseType.WrapInTask().GetName(ambiguousTypes);
147 | }
148 | }
149 |
150 | private static IEnumerable HandleSignatureDuplicates(IEnumerable endpointMethods, HashSet ambiguousTypes)
151 | {
152 | var dictionary = new Dictionary();
153 |
154 | foreach (var endpointMethod in endpointMethods)
155 | {
156 | var parameterTypes = endpointMethod.Parameters.Where(p => !p.IsConstant).Select(p => p.Type.GetName(ambiguousTypes));
157 | var signatureDescription = $"{endpointMethod.Name}({string.Join(",", parameterTypes)})";
158 |
159 | if (dictionary.ContainsKey(signatureDescription))
160 | Console.WriteLine("Duplicate API method " + signatureDescription);
161 |
162 | dictionary[signatureDescription] = endpointMethod;
163 | }
164 |
165 | return dictionary.Values;
166 | }
167 |
168 | private static IEnumerable HandleEndpointDuplicates(IEnumerable endpointMethods, HashSet ambiguousTypes)
169 | {
170 | var dictionary = new Dictionary();
171 |
172 | foreach (var endpointMethod in endpointMethods)
173 | {
174 | var parameterDescriptions = endpointMethod.Parameters.Select(p => $"{p.Source} {p.Type.GetName(ambiguousTypes)} {p.Name} {(p.IsConstant ? ": " + p.DefaultValueLiteral : "")}");
175 | var endpointDescription = $"{endpointMethod.HttpMethod} {endpointMethod.Path} ({string.Join(", ", parameterDescriptions)})";
176 |
177 | if (dictionary.ContainsKey(endpointDescription))
178 | Console.WriteLine("Duplicate API endpoint " + endpointDescription);
179 |
180 | dictionary[endpointDescription] = endpointMethod;
181 | }
182 |
183 | return dictionary.Values;
184 | }
185 |
186 | private static string GetQueryAttribute(Parameter parameter)
187 | {
188 | bool isKeyValuePairs = parameter.Type != typeof(string)
189 | && !parameter.Type.IsAssignableTo(typeof(IDictionary))
190 | && parameter.Type.IsAssignableTo(typeof(IEnumerable));
191 |
192 | if (parameter.Type != typeof(string) && !parameter.Type.IsValueType && !isKeyValuePairs)
193 | return "[Query] ";
194 |
195 | if (!string.Equals(parameter.Name, parameter.ParameterName, StringComparison.OrdinalIgnoreCase))
196 | return $"[AliasAs(\"{parameter.Name}\")] ";
197 |
198 | return "";
199 | }
200 |
201 | private static HashSet GetAmbiguousTypes(IEnumerable clients)
202 | {
203 | var allNamespaces = GetNamespaces(clients.SelectMany(c => c.EndpointMethods));
204 |
205 | return AppDomain.CurrentDomain.GetAssemblies()
206 | .Where(a => !a.IsDynamic)
207 | .SelectMany(a =>
208 | {
209 | try
210 | {
211 | return a.ExportedTypes;
212 | }
213 | catch
214 | {
215 | return [];
216 | }
217 | })
218 | .Where(t => t.DeclaringType == null && allNamespaces.Contains(t.Namespace!))
219 | .GroupBy(t => t.Name)
220 | .Where(g => g.Select(t => t.Namespace).Distinct().Count() > 1)
221 | .SelectMany(g => g)
222 | .ToHashSet();
223 | }
224 |
225 | private static HashSet GetNamespaces(IEnumerable apiDescriptions, HashSet? ambiguousTypes = null)
226 | {
227 | var namespaces = new HashSet();
228 |
229 | foreach (var apiDescription in apiDescriptions)
230 | {
231 | AddForType(apiDescription.ResponseType);
232 |
233 | foreach (var parameterDescription in apiDescription.Parameters)
234 | {
235 | AddForType(parameterDescription.Type);
236 | }
237 | }
238 |
239 | return namespaces;
240 |
241 | void AddForType(Type? type)
242 | {
243 | if (type != null && !type.IsBuiltInType() && ambiguousTypes?.Contains(type) != true)
244 | {
245 | if (type.Namespace != null)
246 | namespaces.Add(type.Namespace);
247 |
248 | if (type.IsGenericType)
249 | {
250 | foreach (var typeArg in type.GetGenericArguments())
251 | AddForType(typeArg);
252 | }
253 | }
254 | }
255 | }
256 |
257 | private class RunSettings : IDisposable
258 | {
259 | private readonly string? environment;
260 | private readonly string? originalEnvironment;
261 | private readonly string originalCurrentDirectory;
262 | private readonly string? originalBaseDirectory;
263 |
264 | public RunSettings(string location, string? environment)
265 | {
266 | this.environment = environment;
267 |
268 | originalEnvironment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
269 | originalCurrentDirectory = Directory.GetCurrentDirectory();
270 | originalBaseDirectory = AppContext.GetData("APP_CONTEXT_BASE_DIRECTORY") as string;
271 |
272 | if (environment != null)
273 | Environment.SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", environment);
274 |
275 | // Update AppContext.BaseDirectory and Directory.CurrentDirectory, since they are often used for json files paths.
276 | SetAppContextBaseDirectory(location);
277 | Directory.SetCurrentDirectory(location);
278 | }
279 |
280 | public void Dispose()
281 | {
282 | if (environment != null)
283 | Environment.SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", originalEnvironment);
284 |
285 | SetAppContextBaseDirectory(originalBaseDirectory);
286 | Directory.SetCurrentDirectory(originalCurrentDirectory);
287 | }
288 |
289 | private static void SetAppContextBaseDirectory(string? path)
290 | {
291 | var setDataMethod = typeof(AppContext).GetMethod("SetData");
292 |
293 | if (setDataMethod != null)
294 | setDataMethod.Invoke(null, new[] { "APP_CONTEXT_BASE_DIRECTORY", path });
295 | }
296 | }
297 | }
298 | }
--------------------------------------------------------------------------------
/GenerateAspNetCoreClient.Command/GroupInfo.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.AspNetCore.Mvc.ApiExplorer;
2 | using Microsoft.AspNetCore.Mvc.Controllers;
3 |
4 | namespace GenerateAspNetCoreClient.Command
5 | {
6 | internal struct GroupInfo
7 | {
8 | public string GroupName { get; set; }
9 | public string? Namespace { get; set; }
10 |
11 | public static GroupInfo From(ApiDescription apiDescription, string? defaultGroupName)
12 | {
13 | var controllerDescriptor = apiDescription.ActionDescriptor as ControllerActionDescriptor;
14 |
15 | return new GroupInfo
16 | {
17 | GroupName = controllerDescriptor?.ControllerName ?? apiDescription.GroupName ?? defaultGroupName ?? "",
18 | Namespace = controllerDescriptor?.ControllerTypeInfo?.Namespace
19 | };
20 | }
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/GenerateAspNetCoreClient.Command/HostFactoryResolver.cs:
--------------------------------------------------------------------------------
1 | // Licensed to the .NET Foundation under one or more agreements.
2 | // The .NET Foundation licenses this file to you under the MIT license.
3 |
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Diagnostics;
7 | using System.Linq;
8 | using System.Reflection;
9 | using System.Threading;
10 | using System.Threading.Tasks;
11 |
12 | #nullable enable
13 |
14 | namespace GenerateAspNetCoreClient.Command
15 | {
16 | internal sealed class HostFactoryResolver
17 | {
18 | private const BindingFlags DeclaredOnlyLookup = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly;
19 |
20 | public const string BuildWebHost = nameof(BuildWebHost);
21 | public const string CreateWebHostBuilder = nameof(CreateWebHostBuilder);
22 | public const string CreateHostBuilder = nameof(CreateHostBuilder);
23 | private const string TimeoutEnvironmentKey = "DOTNET_HOST_FACTORY_RESOLVER_DEFAULT_TIMEOUT_IN_SECONDS";
24 |
25 | // The amount of time we wait for the diagnostic source events to fire
26 | private static readonly TimeSpan s_defaultWaitTimeout = SetupDefaultTimout();
27 |
28 | private static TimeSpan SetupDefaultTimout()
29 | {
30 | if (Debugger.IsAttached)
31 | {
32 | return Timeout.InfiniteTimeSpan;
33 | }
34 |
35 | if (uint.TryParse(Environment.GetEnvironmentVariable(TimeoutEnvironmentKey), out var timeoutInSeconds))
36 | {
37 | return TimeSpan.FromSeconds((int)timeoutInSeconds);
38 | }
39 |
40 | return TimeSpan.FromMinutes(5);
41 | }
42 |
43 | public static Func? ResolveWebHostFactory(Assembly assembly)
44 | {
45 | return ResolveFactory(assembly, BuildWebHost);
46 | }
47 |
48 | public static Func? ResolveWebHostBuilderFactory(Assembly assembly)
49 | {
50 | return ResolveFactory(assembly, CreateWebHostBuilder);
51 | }
52 |
53 | public static Func? ResolveHostBuilderFactory(Assembly assembly)
54 | {
55 | return ResolveFactory(assembly, CreateHostBuilder);
56 | }
57 |
58 | // This helpers encapsulates all of the complex logic required to:
59 | // 1. Execute the entry point of the specified assembly in a different thread.
60 | // 2. Wait for the diagnostic source events to fire
61 | // 3. Give the caller a chance to execute logic to mutate the IHostBuilder
62 | // 4. Resolve the instance of the applications's IHost
63 | // 5. Allow the caller to determine if the entry point has completed
64 | public static Func? ResolveHostFactory(Assembly assembly,
65 | TimeSpan? waitTimeout = null,
66 | bool stopApplication = true,
67 | Action