├── .gitignore └── APIContagem ├── .vscode ├── launch.json └── tasks.json ├── APIContagem.csproj ├── ConfigureSwaggerOptions.cs ├── Contador.cs ├── Program.cs ├── Properties └── launchSettings.json ├── Startup.cs ├── SwaggerDefaultValues.cs ├── V1 ├── Controllers │ └── ContadorController.cs └── Models │ └── ResultadoContador.cs ├── V2 ├── Controllers │ └── ContadorController.cs └── Models │ └── ResultadoContador.cs ├── appsettings.Development.json └── appsettings.json /.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 | # 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 | [Aa][Rr][Mm]/ 27 | [Aa][Rr][Mm]64/ 28 | bld/ 29 | [Bb]in/ 30 | [Oo]bj/ 31 | [Ll]og/ 32 | [Ll]ogs/ 33 | 34 | # Visual Studio 2015/2017 cache/options directory 35 | .vs/ 36 | # Uncomment if you have tasks that create the project's static files in wwwroot 37 | #wwwroot/ 38 | 39 | # Visual Studio 2017 auto generated files 40 | Generated\ Files/ 41 | 42 | # MSTest test Results 43 | [Tt]est[Rr]esult*/ 44 | [Bb]uild[Ll]og.* 45 | 46 | # NUnit 47 | *.VisualState.xml 48 | TestResult.xml 49 | nunit-*.xml 50 | 51 | # Build Results of an ATL Project 52 | [Dd]ebugPS/ 53 | [Rr]eleasePS/ 54 | dlldata.c 55 | 56 | # Benchmark Results 57 | BenchmarkDotNet.Artifacts/ 58 | 59 | # .NET Core 60 | project.lock.json 61 | project.fragment.lock.json 62 | artifacts/ 63 | 64 | # StyleCop 65 | StyleCopReport.xml 66 | 67 | # Files built by Visual Studio 68 | *_i.c 69 | *_p.c 70 | *_h.h 71 | *.ilk 72 | *.meta 73 | *.obj 74 | *.iobj 75 | *.pch 76 | *.pdb 77 | *.ipdb 78 | *.pgc 79 | *.pgd 80 | *.rsp 81 | *.sbr 82 | *.tlb 83 | *.tli 84 | *.tlh 85 | *.tmp 86 | *.tmp_proj 87 | *_wpftmp.csproj 88 | *.log 89 | *.vspscc 90 | *.vssscc 91 | .builds 92 | *.pidb 93 | *.svclog 94 | *.scc 95 | 96 | # Chutzpah Test files 97 | _Chutzpah* 98 | 99 | # Visual C++ cache files 100 | ipch/ 101 | *.aps 102 | *.ncb 103 | *.opendb 104 | *.opensdf 105 | *.sdf 106 | *.cachefile 107 | *.VC.db 108 | *.VC.VC.opendb 109 | 110 | # Visual Studio profiler 111 | *.psess 112 | *.vsp 113 | *.vspx 114 | *.sap 115 | 116 | # Visual Studio Trace Files 117 | *.e2e 118 | 119 | # TFS 2012 Local Workspace 120 | $tf/ 121 | 122 | # Guidance Automation Toolkit 123 | *.gpState 124 | 125 | # ReSharper is a .NET coding add-in 126 | _ReSharper*/ 127 | *.[Rr]e[Ss]harper 128 | *.DotSettings.user 129 | 130 | # TeamCity is a build add-in 131 | _TeamCity* 132 | 133 | # DotCover is a Code Coverage Tool 134 | *.dotCover 135 | 136 | # AxoCover is a Code Coverage Tool 137 | .axoCover/* 138 | !.axoCover/settings.json 139 | 140 | # Visual Studio code coverage results 141 | *.coverage 142 | *.coveragexml 143 | 144 | # NCrunch 145 | _NCrunch_* 146 | .*crunch*.local.xml 147 | nCrunchTemp_* 148 | 149 | # MightyMoose 150 | *.mm.* 151 | AutoTest.Net/ 152 | 153 | # Web workbench (sass) 154 | .sass-cache/ 155 | 156 | # Installshield output folder 157 | [Ee]xpress/ 158 | 159 | # DocProject is a documentation generator add-in 160 | DocProject/buildhelp/ 161 | DocProject/Help/*.HxT 162 | DocProject/Help/*.HxC 163 | DocProject/Help/*.hhc 164 | DocProject/Help/*.hhk 165 | DocProject/Help/*.hhp 166 | DocProject/Help/Html2 167 | DocProject/Help/html 168 | 169 | # Click-Once directory 170 | publish/ 171 | 172 | # Publish Web Output 173 | *.[Pp]ublish.xml 174 | *.azurePubxml 175 | # Note: Comment the next line if you want to checkin your web deploy settings, 176 | # but database connection strings (with potential passwords) will be unencrypted 177 | *.pubxml 178 | *.publishproj 179 | 180 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 181 | # checkin your Azure Web App publish settings, but sensitive information contained 182 | # in these scripts will be unencrypted 183 | PublishScripts/ 184 | 185 | # NuGet Packages 186 | *.nupkg 187 | # NuGet Symbol Packages 188 | *.snupkg 189 | # The packages folder can be ignored because of Package Restore 190 | **/[Pp]ackages/* 191 | # except build/, which is used as an MSBuild target. 192 | !**/[Pp]ackages/build/ 193 | # Uncomment if necessary however generally it will be regenerated when needed 194 | #!**/[Pp]ackages/repositories.config 195 | # NuGet v3's project.json files produces more ignorable files 196 | *.nuget.props 197 | *.nuget.targets 198 | 199 | # Microsoft Azure Build Output 200 | csx/ 201 | *.build.csdef 202 | 203 | # Microsoft Azure Emulator 204 | ecf/ 205 | rcf/ 206 | 207 | # Windows Store app package directories and files 208 | AppPackages/ 209 | BundleArtifacts/ 210 | Package.StoreAssociation.xml 211 | _pkginfo.txt 212 | *.appx 213 | *.appxbundle 214 | *.appxupload 215 | 216 | # Visual Studio cache files 217 | # files ending in .cache can be ignored 218 | *.[Cc]ache 219 | # but keep track of directories ending in .cache 220 | !?*.[Cc]ache/ 221 | 222 | # Others 223 | ClientBin/ 224 | ~$* 225 | *~ 226 | *.dbmdl 227 | *.dbproj.schemaview 228 | *.jfm 229 | *.pfx 230 | *.publishsettings 231 | orleans.codegen.cs 232 | 233 | # Including strong name files can present a security risk 234 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 235 | #*.snk 236 | 237 | # Since there are multiple workflows, uncomment next line to ignore bower_components 238 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 239 | #bower_components/ 240 | 241 | # RIA/Silverlight projects 242 | Generated_Code/ 243 | 244 | # Backup & report files from converting an old project file 245 | # to a newer Visual Studio version. Backup files are not needed, 246 | # because we have git ;-) 247 | _UpgradeReport_Files/ 248 | Backup*/ 249 | UpgradeLog*.XML 250 | UpgradeLog*.htm 251 | ServiceFabricBackup/ 252 | *.rptproj.bak 253 | 254 | # SQL Server files 255 | *.mdf 256 | *.ldf 257 | *.ndf 258 | 259 | # Business Intelligence projects 260 | *.rdl.data 261 | *.bim.layout 262 | *.bim_*.settings 263 | *.rptproj.rsuser 264 | *- [Bb]ackup.rdl 265 | *- [Bb]ackup ([0-9]).rdl 266 | *- [Bb]ackup ([0-9][0-9]).rdl 267 | 268 | # Microsoft Fakes 269 | FakesAssemblies/ 270 | 271 | # GhostDoc plugin setting file 272 | *.GhostDoc.xml 273 | 274 | # Node.js Tools for Visual Studio 275 | .ntvs_analysis.dat 276 | node_modules/ 277 | 278 | # Visual Studio 6 build log 279 | *.plg 280 | 281 | # Visual Studio 6 workspace options file 282 | *.opt 283 | 284 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 285 | *.vbw 286 | 287 | # Visual Studio LightSwitch build output 288 | **/*.HTMLClient/GeneratedArtifacts 289 | **/*.DesktopClient/GeneratedArtifacts 290 | **/*.DesktopClient/ModelManifest.xml 291 | **/*.Server/GeneratedArtifacts 292 | **/*.Server/ModelManifest.xml 293 | _Pvt_Extensions 294 | 295 | # Paket dependency manager 296 | .paket/paket.exe 297 | paket-files/ 298 | 299 | # FAKE - F# Make 300 | .fake/ 301 | 302 | # CodeRush personal settings 303 | .cr/personal 304 | 305 | # Python Tools for Visual Studio (PTVS) 306 | __pycache__/ 307 | *.pyc 308 | 309 | # Cake - Uncomment if you are using it 310 | # tools/** 311 | # !tools/packages.config 312 | 313 | # Tabs Studio 314 | *.tss 315 | 316 | # Telerik's JustMock configuration file 317 | *.jmconfig 318 | 319 | # BizTalk build output 320 | *.btp.cs 321 | *.btm.cs 322 | *.odx.cs 323 | *.xsd.cs 324 | 325 | # OpenCover UI analysis results 326 | OpenCover/ 327 | 328 | # Azure Stream Analytics local run output 329 | ASALocalRun/ 330 | 331 | # MSBuild Binary and Structured Log 332 | *.binlog 333 | 334 | # NVidia Nsight GPU debugger configuration file 335 | *.nvuser 336 | 337 | # MFractors (Xamarin productivity tool) working folder 338 | .mfractor/ 339 | 340 | # Local History for Visual Studio 341 | .localhistory/ 342 | 343 | # BeatPulse healthcheck temp database 344 | healthchecksdb 345 | 346 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 347 | MigrationBackup/ 348 | 349 | # Ionide (cross platform F# VS Code tools) working folder 350 | .ionide/ 351 | -------------------------------------------------------------------------------- /APIContagem/.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to find out which attributes exist for C# debugging 3 | // Use hover for the description of the existing attributes 4 | // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 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/net5.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 | "processId": "${command:pickProcess}" 34 | } 35 | ] 36 | } -------------------------------------------------------------------------------- /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 | "${workspaceFolder}/APIContagem.csproj", 36 | "/property:GenerateFullPaths=true", 37 | "/consoleloggerparameters:NoSummary" 38 | ], 39 | "problemMatcher": "$msCompile" 40 | } 41 | ] 42 | } -------------------------------------------------------------------------------- /APIContagem/APIContagem.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net5.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /APIContagem/ConfigureSwaggerOptions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc.ApiExplorer; 2 | using Microsoft.Extensions.DependencyInjection; 3 | using Microsoft.Extensions.Options; 4 | using Microsoft.OpenApi.Models; 5 | using Swashbuckle.AspNetCore.SwaggerGen; 6 | using System; 7 | 8 | namespace APIContagem 9 | { 10 | /// 11 | /// Configures the Swagger generation options. 12 | /// 13 | /// This allows API versioning to define a Swagger document per API version after the 14 | /// service has been resolved from the service container. 15 | public class ConfigureSwaggerOptions : IConfigureOptions 16 | { 17 | readonly IApiVersionDescriptionProvider provider; 18 | 19 | /// 20 | /// Initializes a new instance of the class. 21 | /// 22 | /// The provider used to generate Swagger documents. 23 | public ConfigureSwaggerOptions( IApiVersionDescriptionProvider provider ) => this.provider = provider; 24 | 25 | /// 26 | public void Configure( SwaggerGenOptions options ) 27 | { 28 | // add a swagger document for each discovered API version 29 | // note: you might choose to skip or document deprecated API versions differently 30 | foreach ( var description in provider.ApiVersionDescriptions ) 31 | { 32 | options.SwaggerDoc( description.GroupName, CreateInfoForApiVersion( description ) ); 33 | } 34 | } 35 | 36 | static OpenApiInfo CreateInfoForApiVersion( ApiVersionDescription description ) 37 | { 38 | var info = new OpenApiInfo() 39 | { 40 | Title = "APIContagem", 41 | Version = description.ApiVersion.ToString(), 42 | Description = "Exemplo com a API de Contagem de Acessos utilizando Swagger, Swashbuckle e API versioning.", 43 | Contact = new OpenApiContact() { Name = "Renato Groffe", Url = new Uri("https://github.com/renatogroffe") }, 44 | License = new OpenApiLicense() { Name = "MIT", Url = new Uri( "https://opensource.org/licenses/MIT" ) } 45 | }; 46 | 47 | if ( description.IsDeprecated ) 48 | { 49 | info.Description += " This API version has been deprecated."; 50 | } 51 | 52 | return info; 53 | } 54 | } 55 | } -------------------------------------------------------------------------------- /APIContagem/Contador.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Reflection; 3 | using System.Runtime.Versioning; 4 | 5 | namespace APIContagem 6 | { 7 | public class Contador 8 | { 9 | private static readonly string _LOCAL; 10 | private static readonly string _KERNEL; 11 | private static readonly string _TARGET_FRAMEWORK; 12 | 13 | static Contador() 14 | { 15 | _LOCAL = Environment.MachineName; 16 | _KERNEL = Environment.OSVersion.VersionString; 17 | _TARGET_FRAMEWORK = Assembly 18 | .GetEntryAssembly()? 19 | .GetCustomAttribute()? 20 | .FrameworkName; 21 | } 22 | 23 | private int _valorAtual = 0; 24 | 25 | public int ValorAtual { get => _valorAtual; } 26 | public string Local { get => _LOCAL; } 27 | public string Kernel { get => _KERNEL; } 28 | public string TargetFramework { get => _TARGET_FRAMEWORK; } 29 | 30 | public void Incrementar() 31 | { 32 | _valorAtual++; 33 | } 34 | } 35 | } -------------------------------------------------------------------------------- /APIContagem/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.AspNetCore.Hosting; 6 | using Microsoft.Extensions.Configuration; 7 | using Microsoft.Extensions.Hosting; 8 | using Microsoft.Extensions.Logging; 9 | 10 | namespace APIContagem 11 | { 12 | public class Program 13 | { 14 | public static void Main(string[] args) 15 | { 16 | CreateHostBuilder(args).Build().Run(); 17 | } 18 | 19 | public static IHostBuilder CreateHostBuilder(string[] args) => 20 | Host.CreateDefaultBuilder(args) 21 | .ConfigureWebHostDefaults(webBuilder => 22 | { 23 | webBuilder.UseStartup(); 24 | }); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /APIContagem/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:60107", 8 | "sslPort": 44336 9 | } 10 | }, 11 | "profiles": { 12 | "IIS Express": { 13 | "commandName": "IISExpress", 14 | "launchBrowser": true, 15 | "launchUrl": "swagger", 16 | "environmentVariables": { 17 | "ASPNETCORE_ENVIRONMENT": "Development" 18 | } 19 | }, 20 | "APIContagem": { 21 | "commandName": "Project", 22 | "dotnetRunMessages": "true", 23 | "launchBrowser": true, 24 | "launchUrl": "swagger", 25 | "applicationUrl": "http://localhost:5000", 26 | "environmentVariables": { 27 | "ASPNETCORE_ENVIRONMENT": "Development" 28 | } 29 | } 30 | } 31 | } -------------------------------------------------------------------------------- /APIContagem/Startup.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Builder; 2 | using Microsoft.AspNetCore.Hosting; 3 | using Microsoft.AspNetCore.Mvc; 4 | using Microsoft.AspNetCore.Mvc.ApiExplorer; 5 | using Microsoft.Extensions.Configuration; 6 | using Microsoft.Extensions.DependencyInjection; 7 | using Microsoft.Extensions.Hosting; 8 | using Microsoft.Extensions.Options; 9 | using Swashbuckle.AspNetCore.SwaggerGen; 10 | 11 | namespace APIContagem 12 | { 13 | public class Startup 14 | { 15 | public Startup(IConfiguration configuration) 16 | { 17 | Configuration = configuration; 18 | } 19 | 20 | public IConfiguration Configuration { get; } 21 | 22 | public void ConfigureServices(IServiceCollection services) 23 | { 24 | services.AddControllers(); 25 | 26 | // GitHub do ASP.NET API Versioning: 27 | // https://github.com/microsoft/aspnet-api-versioning 28 | 29 | // GitHub do projeto que utilizei como base para a 30 | // a implementação desta aplicação: 31 | // https://github.com/microsoft/aspnet-api-versioning/tree/master/samples/aspnetcore/SwaggerSample 32 | 33 | // Algumas referências sobre ASP.NET API Versioning: 34 | // https://devblogs.microsoft.com/aspnet/open-source-http-api-packages-and-tools/ 35 | // https://www.hanselman.com/blog/aspnet-core-restful-web-api-versioning-made-easy 36 | 37 | services.AddApiVersioning(options => 38 | { 39 | // Retorna os headers "api-supported-versions" e "api-deprecated-versions" 40 | // indicando versões suportadas pela API e o que está como deprecated 41 | options.ReportApiVersions = true; 42 | 43 | options.AssumeDefaultVersionWhenUnspecified = true; 44 | options.DefaultApiVersion = new ApiVersion(1, 1); 45 | }); 46 | 47 | services.AddVersionedApiExplorer(options => 48 | { 49 | // Agrupar por número de versão 50 | // add the versioned api explorer, which also adds IApiVersionDescriptionProvider service 51 | // note: the specified format code will format the version as "'v'major[.minor][-status]" 52 | options.GroupNameFormat = "'v'VVV"; 53 | 54 | // Necessário para o correto funcionamento das rotas 55 | // note: this option is only necessary when versioning by url segment. the SubstitutionFormat 56 | // can also be used to control the format of the API version in route templates 57 | options.SubstituteApiVersionInUrl = true; 58 | } ); 59 | 60 | services.AddTransient, ConfigureSwaggerOptions>(); 61 | 62 | /*services.AddSwaggerGen(c => 63 | { 64 | c.SwaggerDoc("v1", new OpenApiInfo { Title = "APIContagem", Version = "v1" }); 65 | });*/ 66 | services.AddSwaggerGen(options => 67 | { 68 | // add a custom operation filter which sets default values 69 | options.OperationFilter(); 70 | } ); 71 | } 72 | 73 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env, 74 | IApiVersionDescriptionProvider provider) 75 | { 76 | if (env.IsDevelopment()) 77 | app.UseDeveloperExceptionPage(); 78 | app.UseSwagger(); 79 | 80 | //app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "APIContagem v1")); 81 | app.UseSwaggerUI(options => 82 | { 83 | // Geração de um endpoint do Swagger para cada versão descoberta 84 | foreach (var description in provider.ApiVersionDescriptions) 85 | { 86 | options.SwaggerEndpoint($"/swagger/{description.GroupName}/swagger.json", 87 | description.GroupName.ToUpperInvariant()); 88 | } 89 | }); 90 | 91 | app.UseCors(builder => builder.AllowAnyMethod() 92 | .AllowAnyOrigin() 93 | .AllowAnyHeader()); 94 | 95 | app.UseHttpsRedirection(); 96 | 97 | app.UseRouting(); 98 | 99 | app.UseEndpoints(endpoints => 100 | { 101 | endpoints.MapControllers(); 102 | }); 103 | } 104 | } 105 | } -------------------------------------------------------------------------------- /APIContagem/SwaggerDefaultValues.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc.ApiExplorer; 2 | using Microsoft.OpenApi.Models; 3 | using Swashbuckle.AspNetCore.SwaggerGen; 4 | using System.Linq; 5 | using System.Text.Json; 6 | 7 | namespace APIContagem 8 | { 9 | /// 10 | /// Represents the Swagger/Swashbuckle operation filter used to document the implicit API version parameter. 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 | /// Applies the filter to the specified operation using the given context. 18 | /// 19 | /// The operation to apply the filter to. 20 | /// The current operation filter context. 21 | public void Apply( OpenApiOperation operation, OperationFilterContext context ) 22 | { 23 | var apiDescription = context.ApiDescription; 24 | 25 | operation.Deprecated |= apiDescription.IsDeprecated(); 26 | 27 | // REF: https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/1752#issue-663991077 28 | foreach ( var responseType in context.ApiDescription.SupportedResponseTypes ) 29 | { 30 | // REF: https://github.com/domaindrivendev/Swashbuckle.AspNetCore/blob/b7cf75e7905050305b115dd96640ddd6e74c7ac9/src/Swashbuckle.AspNetCore.SwaggerGen/SwaggerGenerator/SwaggerGenerator.cs#L383-L387 31 | var responseKey = responseType.IsDefaultResponse ? "default" : responseType.StatusCode.ToString(); 32 | var response = operation.Responses[responseKey]; 33 | 34 | foreach ( var contentType in response.Content.Keys ) 35 | { 36 | if ( !responseType.ApiResponseFormats.Any( x => x.MediaType == contentType ) ) 37 | { 38 | response.Content.Remove( contentType ); 39 | } 40 | } 41 | } 42 | 43 | if ( operation.Parameters == null ) 44 | { 45 | return; 46 | } 47 | 48 | // REF: https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/412 49 | // REF: https://github.com/domaindrivendev/Swashbuckle.AspNetCore/pull/413 50 | foreach ( var parameter in operation.Parameters ) 51 | { 52 | var description = apiDescription.ParameterDescriptions.First( p => p.Name == parameter.Name ); 53 | 54 | if ( parameter.Description == null ) 55 | { 56 | parameter.Description = description.ModelMetadata?.Description; 57 | } 58 | 59 | if ( parameter.Schema.Default == null && description.DefaultValue != null ) 60 | { 61 | // REF: https://github.com/Microsoft/aspnet-api-versioning/issues/429#issuecomment-605402330 62 | var json = JsonSerializer.Serialize( description.DefaultValue, description.ModelMetadata.ModelType ); 63 | parameter.Schema.Default = OpenApiAnyFactory.CreateFromJson( json ); 64 | } 65 | 66 | parameter.Required |= description.IsRequired; 67 | } 68 | } 69 | } 70 | } -------------------------------------------------------------------------------- /APIContagem/V1/Controllers/ContadorController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.AspNetCore.Mvc; 3 | using Microsoft.Extensions.Configuration; 4 | using Microsoft.Extensions.Logging; 5 | using APIContagem.V1.Models; 6 | 7 | namespace APIContagem.V1.Controllers 8 | { 9 | [ApiController] 10 | [ApiVersion("1.0", Deprecated = true)] 11 | [ApiVersion("1.1")] 12 | [Route("[controller]")] 13 | [Route("v{version:apiVersion}/[controller]")] 14 | public class ContadorController : ControllerBase 15 | { 16 | private static readonly Contador _CONTADOR = new Contador(); 17 | private readonly ILogger _logger; 18 | private readonly IConfiguration _configuration; 19 | 20 | public ContadorController(ILogger logger, 21 | IConfiguration configuration) 22 | { 23 | _logger = logger; 24 | _configuration = configuration; 25 | } 26 | 27 | [HttpGet, MapToApiVersion("1.1")] 28 | public ResultadoContador GetV1_1() 29 | { 30 | int valorAtualContador; 31 | lock (_CONTADOR) 32 | { 33 | _CONTADOR.Incrementar(); 34 | valorAtualContador = _CONTADOR.ValorAtual; 35 | } 36 | 37 | return GetResultadoContador(valorAtualContador); 38 | } 39 | 40 | [HttpGet, MapToApiVersion("1.0")] 41 | public ResultadoContador GetV1_0() 42 | { 43 | int valorAtualContador; 44 | lock (_CONTADOR) 45 | { 46 | _CONTADOR.Incrementar(); 47 | valorAtualContador = _CONTADOR.ValorAtual; 48 | } 49 | 50 | if (valorAtualContador % 4 == 0) 51 | { 52 | _logger.LogError("Simulando falha..."); 53 | throw new Exception("Simulação de falha!"); 54 | } 55 | 56 | return GetResultadoContador(valorAtualContador); 57 | } 58 | 59 | private ResultadoContador GetResultadoContador(int valorAtualContador) 60 | { 61 | _logger.LogInformation($"Contador - Valor atual: {valorAtualContador}"); 62 | 63 | return new() 64 | { 65 | ValorAtual = valorAtualContador, 66 | Local = _CONTADOR.Local, 67 | Kernel = _CONTADOR.Kernel, 68 | TargetFramework = _CONTADOR.TargetFramework, 69 | Mensagem = _configuration["MensagemVariavel"] 70 | }; 71 | } 72 | } 73 | } -------------------------------------------------------------------------------- /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 TargetFramework { get; set; } 9 | public object Mensagem { get; set; } 10 | } 11 | } -------------------------------------------------------------------------------- /APIContagem/V2/Controllers/ContadorController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | using Microsoft.Extensions.Configuration; 3 | using Microsoft.Extensions.Logging; 4 | using APIContagem.V2.Models; 5 | 6 | namespace APIContagem.V2.Controllers 7 | { 8 | [ApiController] 9 | [ApiVersion("2.0")] 10 | [Route("[controller]")] 11 | [Route("v{version:apiVersion}/[controller]")] 12 | public class ContadorController : ControllerBase 13 | { 14 | private static readonly Contador _CONTADOR = new Contador(); 15 | private readonly ILogger _logger; 16 | private readonly IConfiguration _configuration; 17 | 18 | public ContadorController(ILogger logger, 19 | IConfiguration configuration) 20 | { 21 | _logger = logger; 22 | _configuration = configuration; 23 | } 24 | 25 | [HttpGet] 26 | public ResultadoContador GetV2_0() 27 | { 28 | int valorAtualContador; 29 | lock (_CONTADOR) 30 | { 31 | _CONTADOR.Incrementar(); 32 | valorAtualContador = _CONTADOR.ValorAtual; 33 | } 34 | 35 | _logger.LogInformation($"Contador - Valor atual: {valorAtualContador}"); 36 | 37 | return new() 38 | { 39 | ValorAtual = valorAtualContador, 40 | Versao = "2.0", 41 | Local = _CONTADOR.Local, 42 | Kernel = _CONTADOR.Kernel, 43 | TargetFramework = _CONTADOR.TargetFramework, 44 | Mensagem = _configuration["MensagemVariavel"] 45 | }; 46 | } 47 | } 48 | } -------------------------------------------------------------------------------- /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 TargetFramework { get; set; } 10 | public object Mensagem { get; set; } 11 | } 12 | } -------------------------------------------------------------------------------- /APIContagem/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /APIContagem/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "MensagemVariavel": "Testes com API Versioning", 3 | "Logging": { 4 | "LogLevel": { 5 | "Default": "Information", 6 | "Microsoft": "Warning", 7 | "Microsoft.Hosting.Lifetime": "Information" 8 | } 9 | }, 10 | "AllowedHosts": "*" 11 | } 12 | --------------------------------------------------------------------------------