├── .gitignore
├── APIContagem
├── .vscode
│ ├── launch.json
│ └── tasks.json
├── APIContagem.csproj
├── Contador.cs
├── Models
│ └── ResultadoContador.cs
├── Program.cs
├── Properties
│ └── launchSettings.json
├── V1
│ ├── Endpoints
│ │ └── ContagemEndpoints.cs
│ └── Models
│ │ └── ResultadoContador.cs
├── V2
│ ├── Endpoints
│ │ └── ContagemEndpoints.cs
│ └── Models
│ │ └── ResultadoContador.cs
├── Versioning
│ ├── ConfigureSwaggerOptions.cs
│ └── SwaggerDefaultValues.cs
├── appsettings.Development.json
└── appsettings.json
└── README.md
/.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/main/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 | # Mono auto generated files
17 | mono_crash.*
18 |
19 | # Build results
20 | [Dd]ebug/
21 | [Dd]ebugPublic/
22 | [Rr]elease/
23 | [Rr]eleases/
24 | x64/
25 | x86/
26 | [Ww][Ii][Nn]32/
27 | [Aa][Rr][Mm]/
28 | [Aa][Rr][Mm]64/
29 | bld/
30 | [Bb]in/
31 | [Oo]bj/
32 | [Ll]og/
33 | [Ll]ogs/
34 |
35 | # Visual Studio 2015/2017 cache/options directory
36 | .vs/
37 | # Uncomment if you have tasks that create the project's static files in wwwroot
38 | #wwwroot/
39 |
40 | # Visual Studio 2017 auto generated files
41 | Generated\ Files/
42 |
43 | # MSTest test Results
44 | [Tt]est[Rr]esult*/
45 | [Bb]uild[Ll]og.*
46 |
47 | # NUnit
48 | *.VisualState.xml
49 | TestResult.xml
50 | nunit-*.xml
51 |
52 | # Build Results of an ATL Project
53 | [Dd]ebugPS/
54 | [Rr]eleasePS/
55 | dlldata.c
56 |
57 | # Benchmark Results
58 | BenchmarkDotNet.Artifacts/
59 |
60 | # .NET Core
61 | project.lock.json
62 | project.fragment.lock.json
63 | artifacts/
64 |
65 | # ASP.NET Scaffolding
66 | ScaffoldingReadMe.txt
67 |
68 | # StyleCop
69 | StyleCopReport.xml
70 |
71 | # Files built by Visual Studio
72 | *_i.c
73 | *_p.c
74 | *_h.h
75 | *.ilk
76 | *.meta
77 | *.obj
78 | *.iobj
79 | *.pch
80 | *.pdb
81 | *.ipdb
82 | *.pgc
83 | *.pgd
84 | *.rsp
85 | *.sbr
86 | *.tlb
87 | *.tli
88 | *.tlh
89 | *.tmp
90 | *.tmp_proj
91 | *_wpftmp.csproj
92 | *.log
93 | *.tlog
94 | *.vspscc
95 | *.vssscc
96 | .builds
97 | *.pidb
98 | *.svclog
99 | *.scc
100 |
101 | # Chutzpah Test files
102 | _Chutzpah*
103 |
104 | # Visual C++ cache files
105 | ipch/
106 | *.aps
107 | *.ncb
108 | *.opendb
109 | *.opensdf
110 | *.sdf
111 | *.cachefile
112 | *.VC.db
113 | *.VC.VC.opendb
114 |
115 | # Visual Studio profiler
116 | *.psess
117 | *.vsp
118 | *.vspx
119 | *.sap
120 |
121 | # Visual Studio Trace Files
122 | *.e2e
123 |
124 | # TFS 2012 Local Workspace
125 | $tf/
126 |
127 | # Guidance Automation Toolkit
128 | *.gpState
129 |
130 | # ReSharper is a .NET coding add-in
131 | _ReSharper*/
132 | *.[Rr]e[Ss]harper
133 | *.DotSettings.user
134 |
135 | # TeamCity is a build add-in
136 | _TeamCity*
137 |
138 | # DotCover is a Code Coverage Tool
139 | *.dotCover
140 |
141 | # AxoCover is a Code Coverage Tool
142 | .axoCover/*
143 | !.axoCover/settings.json
144 |
145 | # Coverlet is a free, cross platform Code Coverage Tool
146 | coverage*.json
147 | coverage*.xml
148 | coverage*.info
149 |
150 | # Visual Studio code coverage results
151 | *.coverage
152 | *.coveragexml
153 |
154 | # NCrunch
155 | _NCrunch_*
156 | .*crunch*.local.xml
157 | nCrunchTemp_*
158 |
159 | # MightyMoose
160 | *.mm.*
161 | AutoTest.Net/
162 |
163 | # Web workbench (sass)
164 | .sass-cache/
165 |
166 | # Installshield output folder
167 | [Ee]xpress/
168 |
169 | # DocProject is a documentation generator add-in
170 | DocProject/buildhelp/
171 | DocProject/Help/*.HxT
172 | DocProject/Help/*.HxC
173 | DocProject/Help/*.hhc
174 | DocProject/Help/*.hhk
175 | DocProject/Help/*.hhp
176 | DocProject/Help/Html2
177 | DocProject/Help/html
178 |
179 | # Click-Once directory
180 | publish/
181 |
182 | # Publish Web Output
183 | *.[Pp]ublish.xml
184 | *.azurePubxml
185 | # Note: Comment the next line if you want to checkin your web deploy settings,
186 | # but database connection strings (with potential passwords) will be unencrypted
187 | *.pubxml
188 | *.publishproj
189 |
190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
191 | # checkin your Azure Web App publish settings, but sensitive information contained
192 | # in these scripts will be unencrypted
193 | PublishScripts/
194 |
195 | # NuGet Packages
196 | *.nupkg
197 | # NuGet Symbol Packages
198 | *.snupkg
199 | # The packages folder can be ignored because of Package Restore
200 | **/[Pp]ackages/*
201 | # except build/, which is used as an MSBuild target.
202 | !**/[Pp]ackages/build/
203 | # Uncomment if necessary however generally it will be regenerated when needed
204 | #!**/[Pp]ackages/repositories.config
205 | # NuGet v3's project.json files produces more ignorable files
206 | *.nuget.props
207 | *.nuget.targets
208 |
209 | # Microsoft Azure Build Output
210 | csx/
211 | *.build.csdef
212 |
213 | # Microsoft Azure Emulator
214 | ecf/
215 | rcf/
216 |
217 | # Windows Store app package directories and files
218 | AppPackages/
219 | BundleArtifacts/
220 | Package.StoreAssociation.xml
221 | _pkginfo.txt
222 | *.appx
223 | *.appxbundle
224 | *.appxupload
225 |
226 | # Visual Studio cache files
227 | # files ending in .cache can be ignored
228 | *.[Cc]ache
229 | # but keep track of directories ending in .cache
230 | !?*.[Cc]ache/
231 |
232 | # Others
233 | ClientBin/
234 | ~$*
235 | *~
236 | *.dbmdl
237 | *.dbproj.schemaview
238 | *.jfm
239 | *.pfx
240 | *.publishsettings
241 | orleans.codegen.cs
242 |
243 | # Including strong name files can present a security risk
244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
245 | #*.snk
246 |
247 | # Since there are multiple workflows, uncomment next line to ignore bower_components
248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
249 | #bower_components/
250 |
251 | # RIA/Silverlight projects
252 | Generated_Code/
253 |
254 | # Backup & report files from converting an old project file
255 | # to a newer Visual Studio version. Backup files are not needed,
256 | # because we have git ;-)
257 | _UpgradeReport_Files/
258 | Backup*/
259 | UpgradeLog*.XML
260 | UpgradeLog*.htm
261 | ServiceFabricBackup/
262 | *.rptproj.bak
263 |
264 | # SQL Server files
265 | *.mdf
266 | *.ldf
267 | *.ndf
268 |
269 | # Business Intelligence projects
270 | *.rdl.data
271 | *.bim.layout
272 | *.bim_*.settings
273 | *.rptproj.rsuser
274 | *- [Bb]ackup.rdl
275 | *- [Bb]ackup ([0-9]).rdl
276 | *- [Bb]ackup ([0-9][0-9]).rdl
277 |
278 | # Microsoft Fakes
279 | FakesAssemblies/
280 |
281 | # GhostDoc plugin setting file
282 | *.GhostDoc.xml
283 |
284 | # Node.js Tools for Visual Studio
285 | .ntvs_analysis.dat
286 | node_modules/
287 |
288 | # Visual Studio 6 build log
289 | *.plg
290 |
291 | # Visual Studio 6 workspace options file
292 | *.opt
293 |
294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
295 | *.vbw
296 |
297 | # Visual Studio 6 auto-generated project file (contains which files were open etc.)
298 | *.vbp
299 |
300 | # Visual Studio 6 workspace and project file (working project files containing files to include in project)
301 | *.dsw
302 | *.dsp
303 |
304 | # Visual Studio 6 technical files
305 | *.ncb
306 | *.aps
307 |
308 | # Visual Studio LightSwitch build output
309 | **/*.HTMLClient/GeneratedArtifacts
310 | **/*.DesktopClient/GeneratedArtifacts
311 | **/*.DesktopClient/ModelManifest.xml
312 | **/*.Server/GeneratedArtifacts
313 | **/*.Server/ModelManifest.xml
314 | _Pvt_Extensions
315 |
316 | # Paket dependency manager
317 | .paket/paket.exe
318 | paket-files/
319 |
320 | # FAKE - F# Make
321 | .fake/
322 |
323 | # CodeRush personal settings
324 | .cr/personal
325 |
326 | # Python Tools for Visual Studio (PTVS)
327 | __pycache__/
328 | *.pyc
329 |
330 | # Cake - Uncomment if you are using it
331 | # tools/**
332 | # !tools/packages.config
333 |
334 | # Tabs Studio
335 | *.tss
336 |
337 | # Telerik's JustMock configuration file
338 | *.jmconfig
339 |
340 | # BizTalk build output
341 | *.btp.cs
342 | *.btm.cs
343 | *.odx.cs
344 | *.xsd.cs
345 |
346 | # OpenCover UI analysis results
347 | OpenCover/
348 |
349 | # Azure Stream Analytics local run output
350 | ASALocalRun/
351 |
352 | # MSBuild Binary and Structured Log
353 | *.binlog
354 |
355 | # NVidia Nsight GPU debugger configuration file
356 | *.nvuser
357 |
358 | # MFractors (Xamarin productivity tool) working folder
359 | .mfractor/
360 |
361 | # Local History for Visual Studio
362 | .localhistory/
363 |
364 | # Visual Studio History (VSHistory) files
365 | .vshistory/
366 |
367 | # BeatPulse healthcheck temp database
368 | healthchecksdb
369 |
370 | # Backup folder for Package Reference Convert tool in Visual Studio 2017
371 | MigrationBackup/
372 |
373 | # Ionide (cross platform F# VS Code tools) working folder
374 | .ionide/
375 |
376 | # Fody - auto-generated XML schema
377 | FodyWeavers.xsd
378 |
379 | # VS Code files for those working on multiple tools
380 | .vscode/*
381 | !.vscode/settings.json
382 | !.vscode/tasks.json
383 | !.vscode/launch.json
384 | !.vscode/extensions.json
385 | *.code-workspace
386 |
387 | # Local History for Visual Studio Code
388 | .history/
389 |
390 | # Windows Installer files from build outputs
391 | *.cab
392 | *.msi
393 | *.msix
394 | *.msm
395 | *.msp
396 |
397 | # JetBrains Rider
398 | *.sln.iml
399 |
--------------------------------------------------------------------------------
/APIContagem/.vscode/launch.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "0.2.0",
3 | "configurations": [
4 | {
5 | // Use IntelliSense to find out which attributes exist for C# debugging
6 | // Use hover for the description of the existing attributes
7 | // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md
8 | "name": ".NET Core Launch (web)",
9 | "type": "coreclr",
10 | "request": "launch",
11 | "preLaunchTask": "build",
12 | // If you have changed target frameworks, make sure to update the program path.
13 | "program": "${workspaceFolder}/bin/Debug/net7.0/APIContagem.dll",
14 | "args": [],
15 | "cwd": "${workspaceFolder}",
16 | "stopAtEntry": false,
17 | // Enable launching a web browser when ASP.NET Core starts. For more information: https://aka.ms/VSCode-CS-LaunchJson-WebBrowser
18 | "serverReadyAction": {
19 | "action": "openExternally",
20 | "pattern": "\\bNow listening on:\\s+(https?://\\S+)"
21 | },
22 | "env": {
23 | "ASPNETCORE_ENVIRONMENT": "Development"
24 | },
25 | "sourceFileMap": {
26 | "/Views": "${workspaceFolder}/Views"
27 | }
28 | },
29 | {
30 | "name": ".NET Core Attach",
31 | "type": "coreclr",
32 | "request": "attach"
33 | }
34 | ]
35 | }
--------------------------------------------------------------------------------
/APIContagem/.vscode/tasks.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "2.0.0",
3 | "tasks": [
4 | {
5 | "label": "build",
6 | "command": "dotnet",
7 | "type": "process",
8 | "args": [
9 | "build",
10 | "${workspaceFolder}/APIContagem.csproj",
11 | "/property:GenerateFullPaths=true",
12 | "/consoleloggerparameters:NoSummary"
13 | ],
14 | "problemMatcher": "$msCompile"
15 | },
16 | {
17 | "label": "publish",
18 | "command": "dotnet",
19 | "type": "process",
20 | "args": [
21 | "publish",
22 | "${workspaceFolder}/APIContagem.csproj",
23 | "/property:GenerateFullPaths=true",
24 | "/consoleloggerparameters:NoSummary"
25 | ],
26 | "problemMatcher": "$msCompile"
27 | },
28 | {
29 | "label": "watch",
30 | "command": "dotnet",
31 | "type": "process",
32 | "args": [
33 | "watch",
34 | "run",
35 | "--project",
36 | "${workspaceFolder}/APIContagem.csproj"
37 | ],
38 | "problemMatcher": "$msCompile"
39 | }
40 | ]
41 | }
--------------------------------------------------------------------------------
/APIContagem/APIContagem.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net7.0
5 | enable
6 | enable
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/APIContagem/Contador.cs:
--------------------------------------------------------------------------------
1 |
2 | using System.Runtime.InteropServices;
3 |
4 | namespace APIContagem;
5 |
6 | public class Contador
7 | {
8 | private static readonly string _LOCAL;
9 | private static readonly string _KERNEL;
10 | private static readonly string _FRAMEWORK;
11 |
12 | static Contador()
13 | {
14 | _LOCAL = Environment.MachineName;
15 | _KERNEL = Environment.OSVersion.VersionString;
16 | _FRAMEWORK = RuntimeInformation.FrameworkDescription;
17 | }
18 |
19 | private int _valorAtual = 0;
20 |
21 | public int ValorAtual { get => _valorAtual; }
22 | public string Local { get => _LOCAL; }
23 | public string Kernel { get => _KERNEL; }
24 | public string Framework { get => _FRAMEWORK; }
25 |
26 | public void Incrementar()
27 | {
28 | _valorAtual++;
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/APIContagem/Models/ResultadoContador.cs:
--------------------------------------------------------------------------------
1 | namespace APIContagem.Models;
2 |
3 | public class ResultadoContador
4 | {
5 | public int ValorAtual { get; set; }
6 | public string? Local { get; set; }
7 | public string? Kernel { get; set; }
8 | public string? Framework { get; set; }
9 | public string? Mensagem { get; set; }
10 | }
--------------------------------------------------------------------------------
/APIContagem/Program.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.Extensions.Options;
2 | using Asp.Versioning;
3 | using Swashbuckle.AspNetCore.SwaggerGen;
4 | using APIContagem.Versioning;
5 | using APIContagem.V1.Endpoints;
6 | using APIContagem.V2.Endpoints;
7 |
8 | // GitHub do ASP.NET API Versioning:
9 | // https://github.com/microsoft/aspnet-api-versioning
10 |
11 | // GitHub do projeto que utilizei como base para a
12 | // a implementacaoo desta aplicacao:
13 | // https://github.com/dotnet/aspnet-api-versioning/tree/2292fbe6a1598d944cd5cbca918cb79da7339116/examples/AspNetCore/WebApi/MinimalOpenApiExample
14 |
15 | // Algumas referencias sobre ASP.NET API Versioning:
16 | // https://renatogroffe.medium.com/net-7-asp-net-core-versionamento-de-apis-rest-em-um-exemplo-simples-8e780a05b249
17 | // https://renatogroffe.medium.com/dica-asp-net-core-versionando-apis-rest-sem-grandes-complica%C3%A7%C3%B5es-1ff3cfcefb2d
18 |
19 | var builder = WebApplication.CreateBuilder(args);
20 | builder.Services.AddEndpointsApiExplorer();
21 | builder.Services
22 | .AddApiVersioning(options =>
23 | {
24 | // Retorna os headers "api-supported-versions" e "api-deprecated-versions"
25 | // indicando versoes suportadas pela API e o que esta como deprecated
26 | options.ReportApiVersions = true;
27 |
28 | options.AssumeDefaultVersionWhenUnspecified = true;
29 | options.DefaultApiVersion = new ApiVersion(1, 2);
30 | })
31 | .AddApiExplorer(
32 | options =>
33 | {
34 | // Agrupar por numero de versao
35 | // add the versioned api explorer, which also adds IApiVersionDescriptionProvider service
36 | // note: the specified format code will format the version as "'v'major[.minor][-status]"
37 | options.GroupNameFormat = "'v'VVV";
38 |
39 | // Necessario para o correto funcionamento das rotas
40 | // note: this option is only necessary when versioning by url segment. the SubstitutionFormat
41 | // can also be used to control the format of the API version in route templates
42 | options.SubstituteApiVersionInUrl = true;
43 | })
44 | // this enables binding ApiVersion as a endpoint callback parameter. if you don't use it, then
45 | // you should remove this configuration.
46 | .EnableApiVersionBinding();
47 | builder.Services.AddTransient, ConfigureSwaggerOptions>();
48 | builder.Services.AddSwaggerGen( options => options.OperationFilter() );
49 |
50 | builder.Services.AddCors();
51 |
52 | var app = builder.Build();
53 |
54 | app.UseCors(policy => policy.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
55 |
56 | var apiContagem = app.NewVersionedApi("Contagem");
57 | apiContagem.MapEndpointsContagemV1("/contador", app.Logger);
58 | apiContagem.MapEndpointsContagemV1("/v{version:apiVersion}/contador", app.Logger);
59 | apiContagem.MapEndpointsContagemV2("/contador", app.Logger);
60 | apiContagem.MapEndpointsContagemV2("/v{version:apiVersion}/contador", app.Logger);
61 |
62 | app.UseSwagger();
63 | app.UseSwaggerUI(
64 | options =>
65 | {
66 | var descriptions = app.DescribeApiVersions();
67 |
68 | // build a swagger endpoint for each discovered API version
69 | foreach ( var description in descriptions )
70 | {
71 | var url = $"/swagger/{description.GroupName}/swagger.json";
72 | var name = description.GroupName.ToUpperInvariant();
73 | options.SwaggerEndpoint( url, name );
74 | }
75 | } );
76 |
77 | app.Run();
--------------------------------------------------------------------------------
/APIContagem/Properties/launchSettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "iisSettings": {
3 | "windowsAuthentication": false,
4 | "anonymousAuthentication": true,
5 | "iisExpress": {
6 | "applicationUrl": "http://localhost:16084",
7 | "sslPort": 44343
8 | }
9 | },
10 | "profiles": {
11 | "http": {
12 | "commandName": "Project",
13 | "dotnetRunMessages": true,
14 | "launchBrowser": true,
15 | "applicationUrl": "http://localhost:5245",
16 | "environmentVariables": {
17 | "ASPNETCORE_ENVIRONMENT": "Development"
18 | }
19 | },
20 | "https": {
21 | "commandName": "Project",
22 | "dotnetRunMessages": true,
23 | "launchBrowser": true,
24 | "applicationUrl": "https://localhost:7180;http://localhost:5245",
25 | "environmentVariables": {
26 | "ASPNETCORE_ENVIRONMENT": "Development"
27 | }
28 | },
29 | "IIS Express": {
30 | "commandName": "IISExpress",
31 | "launchBrowser": true,
32 | "environmentVariables": {
33 | "ASPNETCORE_ENVIRONMENT": "Development"
34 | }
35 | }
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/APIContagem/V1/Endpoints/ContagemEndpoints.cs:
--------------------------------------------------------------------------------
1 | using Asp.Versioning;
2 | using Asp.Versioning.Builder;
3 | using APIContagem.V1.Models;
4 |
5 | namespace APIContagem.V1.Endpoints;
6 |
7 | public static class ContagemEndpoints
8 | {
9 | private static readonly Contador _CONTADOR = new ();
10 |
11 | public static IVersionedEndpointRouteBuilder? MapEndpointsContagemV1(
12 | this IVersionedEndpointRouteBuilder? versionedBuilder, string routePrefix, ILogger logger)
13 | {
14 | var contagemV1 = versionedBuilder!.MapGroup(routePrefix)
15 | .HasDeprecatedApiVersion(new ApiVersion(1, 0))
16 | .HasApiVersion(new ApiVersion(1, 1))
17 | .HasApiVersion(new ApiVersion(1, 2));
18 |
19 | contagemV1.MapGet("/", () =>
20 | {
21 | int valorAtualContador;
22 | lock (_CONTADOR)
23 | {
24 | _CONTADOR.Incrementar();
25 | valorAtualContador = _CONTADOR.ValorAtual;
26 | }
27 | logger.LogInformation($"Contador 1.0 (Deprecated) - Valor atual: {valorAtualContador}");
28 | if (valorAtualContador % 4 == 0)
29 | {
30 | logger.LogError("Simulando falha...");
31 | throw new Exception("Simulação de falha!");
32 | }
33 | return TypedResults.Ok(new ResultadoContador()
34 | {
35 | ValorAtual = _CONTADOR.ValorAtual,
36 | Local = _CONTADOR.Local,
37 | Kernel = _CONTADOR.Kernel,
38 | Framework = _CONTADOR.Framework,
39 | Mensagem = $"Versao 1.0 (Deprecated)"
40 | });
41 | }).Produces()
42 | .MapToApiVersion(new ApiVersion(1, 0));
43 |
44 | contagemV1.MapGet("/", () =>
45 | {
46 | int valorAtualContador;
47 | lock (_CONTADOR)
48 | {
49 | _CONTADOR.Incrementar();
50 | valorAtualContador = _CONTADOR.ValorAtual;
51 | }
52 | logger.LogInformation($"Contador 1.x - Valor atual: {valorAtualContador}");
53 | return TypedResults.Ok(new ResultadoContador()
54 | {
55 | ValorAtual = _CONTADOR.ValorAtual,
56 | Local = _CONTADOR.Local,
57 | Kernel = _CONTADOR.Kernel,
58 | Framework = _CONTADOR.Framework,
59 | Mensagem = $"Versao 1.x"
60 | });
61 | }).Produces()
62 | .MapToApiVersion(new ApiVersion(1, 1))
63 | .MapToApiVersion(new ApiVersion(1, 2));
64 |
65 | return versionedBuilder;
66 | }
67 | }
--------------------------------------------------------------------------------
/APIContagem/V1/Models/ResultadoContador.cs:
--------------------------------------------------------------------------------
1 | namespace APIContagem.V1.Models;
2 |
3 | public class ResultadoContador
4 | {
5 | public int ValorAtual { get; set; }
6 | public string? Local { get; set; }
7 | public string? Kernel { get; set; }
8 | public string? Framework { get; set; }
9 | public string? Mensagem { get; set; }
10 | }
--------------------------------------------------------------------------------
/APIContagem/V2/Endpoints/ContagemEndpoints.cs:
--------------------------------------------------------------------------------
1 | using Asp.Versioning;
2 | using Asp.Versioning.Builder;
3 | using APIContagem.V2.Models;
4 |
5 | namespace APIContagem.V2.Endpoints;
6 |
7 | public static class ContagemEndpoints
8 | {
9 | private static readonly Contador _CONTADOR = new ();
10 |
11 | public static IVersionedEndpointRouteBuilder? MapEndpointsContagemV2(
12 | this IVersionedEndpointRouteBuilder? versionedBuilder, string routePrefix, ILogger logger)
13 | {
14 | var contagemV2 = versionedBuilder!.MapGroup(routePrefix)
15 | .HasApiVersion(new ApiVersion(2, 0));
16 |
17 | contagemV2.MapGet("/", () =>
18 | {
19 | int valorAtualContador;
20 | lock (_CONTADOR)
21 | {
22 | _CONTADOR.Incrementar();
23 | valorAtualContador = _CONTADOR.ValorAtual;
24 | }
25 | logger.LogInformation($"Contador 2.0 - Valor atual: {valorAtualContador}");
26 | return TypedResults.Ok(new ResultadoContador()
27 | {
28 | ValorAtual = _CONTADOR.ValorAtual,
29 | Versao = "2.0",
30 | Local = _CONTADOR.Local,
31 | Kernel = _CONTADOR.Kernel,
32 | Framework = _CONTADOR.Framework,
33 | Mensagem = "Testes com Minimal APIs e API Versioning"
34 | });
35 | }).Produces()
36 | .MapToApiVersion(new ApiVersion(2, 0));
37 |
38 | return versionedBuilder;
39 | }
40 | }
--------------------------------------------------------------------------------
/APIContagem/V2/Models/ResultadoContador.cs:
--------------------------------------------------------------------------------
1 | namespace APIContagem.V2.Models;
2 |
3 | public class ResultadoContador
4 | {
5 | public int ValorAtual { get; set; }
6 | public string? Versao { get; set; }
7 | public string? Local { get; set; }
8 | public string? Kernel { get; set; }
9 | public string? Framework { get; set; }
10 | public string? Mensagem { get; set; }
11 | }
--------------------------------------------------------------------------------
/APIContagem/Versioning/ConfigureSwaggerOptions.cs:
--------------------------------------------------------------------------------
1 | using Asp.Versioning;
2 | using Asp.Versioning.ApiExplorer;
3 | using Microsoft.Extensions.DependencyInjection;
4 | using Microsoft.Extensions.Options;
5 | using Microsoft.OpenApi.Models;
6 | using Swashbuckle.AspNetCore.SwaggerGen;
7 | using System.Text;
8 |
9 | namespace APIContagem.Versioning;
10 |
11 | ///
12 | /// Configures the Swagger generation options.
13 | ///
14 | /// This allows API versioning to define a Swagger document per API version after the
15 | /// service has been resolved from the service container.
16 | public class ConfigureSwaggerOptions : IConfigureOptions
17 | {
18 | private readonly IApiVersionDescriptionProvider provider;
19 |
20 | ///
21 | /// Initializes a new instance of the class.
22 | ///
23 | /// The provider used to generate Swagger documents.
24 | public ConfigureSwaggerOptions( IApiVersionDescriptionProvider provider ) => this.provider = provider;
25 |
26 | ///
27 | public void Configure( SwaggerGenOptions options )
28 | {
29 | // add a swagger document for each discovered API version
30 | // note: you might choose to skip or document deprecated API versions differently
31 | foreach ( var description in provider.ApiVersionDescriptions )
32 | {
33 | options.SwaggerDoc( description.GroupName, CreateInfoForApiVersion( description ) );
34 | }
35 | }
36 |
37 | private static OpenApiInfo CreateInfoForApiVersion( ApiVersionDescription description )
38 | {
39 | var text = new StringBuilder( "Exemplo com a API de Contagem de Acessos utilizando Minimal APIs, Swagger, Swashbuckle e API versioning." );
40 | var info = new OpenApiInfo()
41 | {
42 | Title = "APIContagem",
43 | Version = description.ApiVersion.ToString(),
44 | Contact = new OpenApiContact() { Name = "Renato Groffe", Url = new Uri("https://github.com/renatogroffe") },
45 | License = new OpenApiLicense() { Name = "MIT", Url = new Uri("https://opensource.org/licenses/MIT") }
46 | };
47 |
48 | if ( description.IsDeprecated )
49 | {
50 | text.Append( " This API version has been deprecated." );
51 | }
52 |
53 | if ( description.SunsetPolicy is SunsetPolicy policy )
54 | {
55 | if ( policy.Date is DateTimeOffset when )
56 | {
57 | text.Append( " The API will be sunset on " )
58 | .Append( when.Date.ToShortDateString() )
59 | .Append( '.' );
60 | }
61 |
62 | if ( policy.HasLinks )
63 | {
64 | text.AppendLine();
65 |
66 | for ( var i = 0; i < policy.Links.Count; i++ )
67 | {
68 | var link = policy.Links[i];
69 |
70 | if ( link.Type == "text/html" )
71 | {
72 | text.AppendLine();
73 |
74 | if ( link.Title.HasValue )
75 | {
76 | text.Append( link.Title.Value ).Append( ": " );
77 | }
78 |
79 | text.Append( link.LinkTarget.OriginalString );
80 | }
81 | }
82 | }
83 | }
84 |
85 | info.Description = text.ToString();
86 |
87 | return info;
88 | }
89 | }
--------------------------------------------------------------------------------
/APIContagem/Versioning/SwaggerDefaultValues.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.AspNetCore.Mvc.ApiExplorer;
2 | using Microsoft.AspNetCore.Mvc.ModelBinding;
3 | using Microsoft.OpenApi.Models;
4 | using Swashbuckle.AspNetCore.SwaggerGen;
5 | using System.Text.Json;
6 |
7 | namespace APIContagem.Versioning;
8 |
9 | ///
10 | /// Represents the OpenAPI/Swashbuckle operation filter used to document information provided, but not used.
11 | ///
12 | /// This is only required due to bugs in the .
13 | /// Once they are fixed and published, this class can be removed.
14 | public class SwaggerDefaultValues : IOperationFilter
15 | {
16 | ///
17 | public void Apply( OpenApiOperation operation, OperationFilterContext context )
18 | {
19 | var apiDescription = context.ApiDescription;
20 |
21 | operation.Deprecated |= apiDescription.IsDeprecated();
22 |
23 | // REF: https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/1752#issue-663991077
24 | foreach ( var responseType in context.ApiDescription.SupportedResponseTypes )
25 | {
26 | // REF: https://github.com/domaindrivendev/Swashbuckle.AspNetCore/blob/b7cf75e7905050305b115dd96640ddd6e74c7ac9/src/Swashbuckle.AspNetCore.SwaggerGen/SwaggerGenerator/SwaggerGenerator.cs#L383-L387
27 | var responseKey = responseType.IsDefaultResponse ? "default" : responseType.StatusCode.ToString();
28 | var response = operation.Responses[responseKey];
29 |
30 | foreach ( var contentType in response.Content.Keys )
31 | {
32 | if ( !responseType.ApiResponseFormats.Any( x => x.MediaType == contentType ) )
33 | {
34 | response.Content.Remove( contentType );
35 | }
36 | }
37 | }
38 |
39 | if ( operation.Parameters == null )
40 | {
41 | return;
42 | }
43 |
44 | // REF: https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/412
45 | // REF: https://github.com/domaindrivendev/Swashbuckle.AspNetCore/pull/413
46 | foreach ( var parameter in operation.Parameters )
47 | {
48 | var description = apiDescription.ParameterDescriptions.First( p => p.Name == parameter.Name );
49 |
50 | parameter.Description ??= description.ModelMetadata?.Description;
51 |
52 | if ( parameter.Schema.Default == null &&
53 | description.DefaultValue != null &&
54 | description.DefaultValue is not DBNull &&
55 | description.ModelMetadata is ModelMetadata modelMetadata )
56 | {
57 | // REF: https://github.com/Microsoft/aspnet-api-versioning/issues/429#issuecomment-605402330
58 | var json = JsonSerializer.Serialize( description.DefaultValue, modelMetadata.ModelType );
59 | parameter.Schema.Default = OpenApiAnyFactory.CreateFromJson( json );
60 | }
61 |
62 | parameter.Required |= description.IsRequired;
63 | }
64 | }
65 | }
--------------------------------------------------------------------------------
/APIContagem/appsettings.Development.json:
--------------------------------------------------------------------------------
1 | {
2 | "Logging": {
3 | "LogLevel": {
4 | "Default": "Information",
5 | "Microsoft.AspNetCore": "Warning"
6 | }
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/APIContagem/appsettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "Logging": {
3 | "LogLevel": {
4 | "Default": "Information",
5 | "Microsoft.AspNetCore": "Warning"
6 | }
7 | },
8 | "AllowedHosts": "*"
9 | }
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # ASPNETCore7-MinimalAPIs-Swagger-Versioning_ContagemAcessos
2 | Exemplo de API REST com versionamento criada com o ASP.NET Core + .NET 7 + Minimal APIs para contagem de acessos, com utilização do Swagger e do projeto ASP.NET API Versioning (informando número da versão na URL e via Query String).
3 |
4 | Patterns para versionamento de APIs:
5 | **https://microservice-api-patterns.org/patterns/evolution/**
6 |
--------------------------------------------------------------------------------