├── .github └── workflows │ └── main.yml ├── .gitignore ├── .vscode ├── launch.json ├── settings.json └── tasks.json ├── MinimalApi.sln ├── README.md ├── Source ├── .vscode │ ├── launch.json │ └── tasks.json ├── ApiVersionOperationFilter.cs ├── AuthorizationHeaderOperationHeader.cs ├── Data │ ├── Migrations │ │ ├── 20211111034925_InitialMigrations.Designer.cs │ │ ├── 20211111034925_InitialMigrations.cs │ │ ├── 20211123093642_UserTableAdded.Designer.cs │ │ ├── 20211123093642_UserTableAdded.cs │ │ ├── 20211201054707_UsersTableSetAsTemporal.Designer.cs │ │ ├── 20211201054707_UsersTableSetAsTemporal.cs │ │ └── TodoDbContextModelSnapshot.cs │ └── TodoDbContext.cs ├── MinimalApi.csproj ├── Models │ ├── TodoItem.cs │ ├── TodoItemAudit.cs │ └── User.cs ├── Program.cs ├── Properties │ └── launchSettings.json ├── TodoApi.cs ├── Usings.cs ├── ViewModels │ ├── PagedResults.cs │ ├── TodoItemInput.cs │ ├── TodoItemInputValidator.cs │ ├── TodoItemOutput.cs │ ├── UserInput.cs │ └── UserInputValidator.cs ├── appsettings.Development.json └── appsettings.json ├── Tests ├── .vscode │ ├── launch.json │ └── tasks.json ├── MinimalApi.Tests.csproj ├── TodoApiIntegrationTests.cs ├── TodoApiTests.cs └── Usings.cs └── nuget.config /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | # This is a basic workflow to help you get started with Actions 2 | 3 | name: CI 4 | 5 | # Controls when the workflow will run 6 | on: 7 | # Triggers the workflow on push or pull request events but only for the main branch 8 | push: 9 | branches: [main] 10 | paths-ignore: 11 | - "README.md" 12 | pull_request: 13 | branches: [main] 14 | paths-ignore: 15 | - "README.md" 16 | 17 | # Allows you to run this workflow manually from the Actions tab 18 | workflow_dispatch: 19 | 20 | jobs: 21 | build: 22 | runs-on: ubuntu-latest 23 | 24 | steps: 25 | - uses: actions/checkout@v4.2.2 26 | - name: set release date 27 | run: | 28 | echo "BUILD_VERSION=$(date --rfc-3339=date)" >> ${GITHUB_ENV} 29 | - name: Set up .NET Core 30 | uses: actions/setup-dotnet@v4.3.0 31 | with: 32 | dotnet-version: "8.0.x" 33 | dotnet-quality: "preview" 34 | 35 | - name: Build with dotnet 36 | run: dotnet build --configuration Release 37 | 38 | - name: Install Required Tools 39 | run: | 40 | dotnet new tool-manifest 41 | dotnet tool install dotnet-reportgenerator-globaltool 42 | dotnet tool install dotnet-coverage 43 | - name: Run the unit tests with code coverage 44 | run: dotnet coverage collect dotnet test --filter TodoApiTests --output ${{ github.workspace }}/Tests/Coverage.cobertura.xml --output-format cobertura 45 | - name: Generate Report 46 | run: | 47 | dotnet reportgenerator -reports:${{ github.workspace }}/Tests/Coverage.cobertura.xml -targetdir:"${{ github.workspace }}/Tests/coveragereport" -reporttypes:"MarkdownSummary;Html" -assemblyfilters:+MinimalApi 48 | - name: Upload code coverage report 49 | uses: actions/upload-artifact@v4.6.0 50 | with: 51 | name: coveragereport 52 | path: ${{ github.workspace }}/Tests/coveragereport 53 | - name: Add Coverage PR Comment 54 | uses: marocchino/sticky-pull-request-comment@v2 55 | if: github.event_name == 'pull_request' 56 | with: 57 | recreate: true 58 | path: ${{ github.workspace }}/Tests/coveragereport/Summary.md 59 | 60 | - name: Configuring Tokens 61 | working-directory: ./Source 62 | run: | 63 | echo "USER1_TOKEN=$(dotnet user-jwts create --claim Username=user1 --claim Email=user1@example.com --name user1 --output token)" >> $GITHUB_ENV 64 | echo "USER2_TOKEN=$(dotnet user-jwts create --claim Username=user2 --claim Email=user2@example.com --name user2 --output token)" >> $GITHUB_ENV 65 | - name: Running Integration Tests 66 | run: dotnet test --filter TodoApiIntegrationTests 67 | 68 | - name: dotnet publish 69 | run: dotnet publish -c Release -o ${{ github.workspace }}/myapp 70 | 71 | - name: dotnet publish to Docker 72 | run: dotnet publish --os linux --arch x64 -p:PublishProfile=DefaultContainer 73 | 74 | - name: Upload artifact for deployment job 75 | uses: actions/upload-artifact@v4.6.0 76 | with: 77 | name: .net-app 78 | path: ${{ github.workspace }}/myapp 79 | 80 | - name: Login with Github Container registry 81 | uses: docker/login-action@v3.3.0 82 | with: 83 | registry: ghcr.io 84 | username: ${{ github.actor }} 85 | password: ${{ secrets.GITHUB_TOKEN }} 86 | 87 | - name: Publish to Github Container registry 88 | run: docker push ghcr.io/anuraj/minimalapi:${{ env.BUILD_VERSION }} 89 | -------------------------------------------------------------------------------- /.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 | [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 | # Tye 66 | .tye/ 67 | 68 | # ASP.NET Scaffolding 69 | ScaffoldingReadMe.txt 70 | 71 | # StyleCop 72 | StyleCopReport.xml 73 | 74 | # Files built by Visual Studio 75 | *_i.c 76 | *_p.c 77 | *_h.h 78 | *.ilk 79 | *.meta 80 | *.obj 81 | *.iobj 82 | *.pch 83 | *.pdb 84 | *.ipdb 85 | *.pgc 86 | *.pgd 87 | *.rsp 88 | *.sbr 89 | *.tlb 90 | *.tli 91 | *.tlh 92 | *.tmp 93 | *.tmp_proj 94 | *_wpftmp.csproj 95 | *.log 96 | *.vspscc 97 | *.vssscc 98 | .builds 99 | *.pidb 100 | *.svclog 101 | *.scc 102 | 103 | # Chutzpah Test files 104 | _Chutzpah* 105 | 106 | # Visual C++ cache files 107 | ipch/ 108 | *.aps 109 | *.ncb 110 | *.opendb 111 | *.opensdf 112 | *.sdf 113 | *.cachefile 114 | *.VC.db 115 | *.VC.VC.opendb 116 | 117 | # Visual Studio profiler 118 | *.psess 119 | *.vsp 120 | *.vspx 121 | *.sap 122 | 123 | # Visual Studio Trace Files 124 | *.e2e 125 | 126 | # TFS 2012 Local Workspace 127 | $tf/ 128 | 129 | # Guidance Automation Toolkit 130 | *.gpState 131 | 132 | # ReSharper is a .NET coding add-in 133 | _ReSharper*/ 134 | *.[Rr]e[Ss]harper 135 | *.DotSettings.user 136 | 137 | # TeamCity is a build add-in 138 | _TeamCity* 139 | 140 | # DotCover is a Code Coverage Tool 141 | *.dotCover 142 | 143 | # AxoCover is a Code Coverage Tool 144 | .axoCover/* 145 | !.axoCover/settings.json 146 | 147 | # Coverlet is a free, cross platform Code Coverage Tool 148 | coverage*.json 149 | coverage*.xml 150 | coverage*.info 151 | 152 | # Visual Studio code coverage results 153 | *.coverage 154 | *.coveragexml 155 | 156 | # NCrunch 157 | _NCrunch_* 158 | .*crunch*.local.xml 159 | nCrunchTemp_* 160 | 161 | # MightyMoose 162 | *.mm.* 163 | AutoTest.Net/ 164 | 165 | # Web workbench (sass) 166 | .sass-cache/ 167 | 168 | # Installshield output folder 169 | [Ee]xpress/ 170 | 171 | # DocProject is a documentation generator add-in 172 | DocProject/buildhelp/ 173 | DocProject/Help/*.HxT 174 | DocProject/Help/*.HxC 175 | DocProject/Help/*.hhc 176 | DocProject/Help/*.hhk 177 | DocProject/Help/*.hhp 178 | DocProject/Help/Html2 179 | DocProject/Help/html 180 | 181 | # Click-Once directory 182 | publish/ 183 | 184 | # Publish Web Output 185 | *.[Pp]ublish.xml 186 | *.azurePubxml 187 | # Note: Comment the next line if you want to checkin your web deploy settings, 188 | # but database connection strings (with potential passwords) will be unencrypted 189 | *.pubxml 190 | *.publishproj 191 | 192 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 193 | # checkin your Azure Web App publish settings, but sensitive information contained 194 | # in these scripts will be unencrypted 195 | PublishScripts/ 196 | 197 | # NuGet Packages 198 | *.nupkg 199 | # NuGet Symbol Packages 200 | *.snupkg 201 | # The packages folder can be ignored because of Package Restore 202 | **/[Pp]ackages/* 203 | # except build/, which is used as an MSBuild target. 204 | !**/[Pp]ackages/build/ 205 | # Uncomment if necessary however generally it will be regenerated when needed 206 | #!**/[Pp]ackages/repositories.config 207 | # NuGet v3's project.json files produces more ignorable files 208 | *.nuget.props 209 | *.nuget.targets 210 | 211 | # Microsoft Azure Build Output 212 | csx/ 213 | *.build.csdef 214 | 215 | # Microsoft Azure Emulator 216 | ecf/ 217 | rcf/ 218 | 219 | # Windows Store app package directories and files 220 | AppPackages/ 221 | BundleArtifacts/ 222 | Package.StoreAssociation.xml 223 | _pkginfo.txt 224 | *.appx 225 | *.appxbundle 226 | *.appxupload 227 | 228 | # Visual Studio cache files 229 | # files ending in .cache can be ignored 230 | *.[Cc]ache 231 | # but keep track of directories ending in .cache 232 | !?*.[Cc]ache/ 233 | 234 | # Others 235 | ClientBin/ 236 | ~$* 237 | *~ 238 | *.dbmdl 239 | *.dbproj.schemaview 240 | *.jfm 241 | *.pfx 242 | *.publishsettings 243 | orleans.codegen.cs 244 | 245 | # Including strong name files can present a security risk 246 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 247 | #*.snk 248 | 249 | # Since there are multiple workflows, uncomment next line to ignore bower_components 250 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 251 | #bower_components/ 252 | 253 | # RIA/Silverlight projects 254 | Generated_Code/ 255 | 256 | # Backup & report files from converting an old project file 257 | # to a newer Visual Studio version. Backup files are not needed, 258 | # because we have git ;-) 259 | _UpgradeReport_Files/ 260 | Backup*/ 261 | UpgradeLog*.XML 262 | UpgradeLog*.htm 263 | ServiceFabricBackup/ 264 | *.rptproj.bak 265 | 266 | # SQL Server files 267 | *.mdf 268 | *.ldf 269 | *.ndf 270 | 271 | # Business Intelligence projects 272 | *.rdl.data 273 | *.bim.layout 274 | *.bim_*.settings 275 | *.rptproj.rsuser 276 | *- [Bb]ackup.rdl 277 | *- [Bb]ackup ([0-9]).rdl 278 | *- [Bb]ackup ([0-9][0-9]).rdl 279 | 280 | # Microsoft Fakes 281 | FakesAssemblies/ 282 | 283 | # GhostDoc plugin setting file 284 | *.GhostDoc.xml 285 | 286 | # Node.js Tools for Visual Studio 287 | .ntvs_analysis.dat 288 | node_modules/ 289 | 290 | # Visual Studio 6 build log 291 | *.plg 292 | 293 | # Visual Studio 6 workspace options file 294 | *.opt 295 | 296 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 297 | *.vbw 298 | 299 | # Visual Studio LightSwitch build output 300 | **/*.HTMLClient/GeneratedArtifacts 301 | **/*.DesktopClient/GeneratedArtifacts 302 | **/*.DesktopClient/ModelManifest.xml 303 | **/*.Server/GeneratedArtifacts 304 | **/*.Server/ModelManifest.xml 305 | _Pvt_Extensions 306 | 307 | # Paket dependency manager 308 | .paket/paket.exe 309 | paket-files/ 310 | 311 | # FAKE - F# Make 312 | .fake/ 313 | 314 | # CodeRush personal settings 315 | .cr/personal 316 | 317 | # Python Tools for Visual Studio (PTVS) 318 | __pycache__/ 319 | *.pyc 320 | 321 | # Cake - Uncomment if you are using it 322 | # tools/** 323 | # !tools/packages.config 324 | 325 | # Tabs Studio 326 | *.tss 327 | 328 | # Telerik's JustMock configuration file 329 | *.jmconfig 330 | 331 | # BizTalk build output 332 | *.btp.cs 333 | *.btm.cs 334 | *.odx.cs 335 | *.xsd.cs 336 | 337 | # OpenCover UI analysis results 338 | OpenCover/ 339 | 340 | # Azure Stream Analytics local run output 341 | ASALocalRun/ 342 | 343 | # MSBuild Binary and Structured Log 344 | *.binlog 345 | 346 | # NVidia Nsight GPU debugger configuration file 347 | *.nvuser 348 | 349 | # MFractors (Xamarin productivity tool) working folder 350 | .mfractor/ 351 | 352 | # Local History for Visual Studio 353 | .localhistory/ 354 | 355 | # BeatPulse healthcheck temp database 356 | healthchecksdb 357 | 358 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 359 | MigrationBackup/ 360 | 361 | # Ionide (cross platform F# VS Code tools) working folder 362 | .ionide/ 363 | 364 | # Fody - auto-generated XML schema 365 | FodyWeavers.xsd 366 | 367 | ## 368 | ## Visual studio for Mac 369 | ## 370 | 371 | 372 | # globs 373 | Makefile.in 374 | *.userprefs 375 | *.usertasks 376 | config.make 377 | config.status 378 | aclocal.m4 379 | install-sh 380 | autom4te.cache/ 381 | *.tar.gz 382 | tarballs/ 383 | test-results/ 384 | 385 | # Mac bundle stuff 386 | *.dmg 387 | *.app 388 | 389 | # content below from: https://github.com/github/gitignore/blob/master/Global/macOS.gitignore 390 | # General 391 | .DS_Store 392 | .AppleDouble 393 | .LSOverride 394 | 395 | # Icon must end with two \r 396 | Icon 397 | 398 | 399 | # Thumbnails 400 | ._* 401 | 402 | # Files that might appear in the root of a volume 403 | .DocumentRevisions-V100 404 | .fseventsd 405 | .Spotlight-V100 406 | .TemporaryItems 407 | .Trashes 408 | .VolumeIcon.icns 409 | .com.apple.timemachine.donotpresent 410 | 411 | # Directories potentially created on remote AFP share 412 | .AppleDB 413 | .AppleDesktop 414 | Network Trash Folder 415 | Temporary Items 416 | .apdisk 417 | 418 | # content below from: https://github.com/github/gitignore/blob/master/Global/Windows.gitignore 419 | # Windows thumbnail cache files 420 | Thumbs.db 421 | ehthumbs.db 422 | ehthumbs_vista.db 423 | 424 | # Dump file 425 | *.stackdump 426 | 427 | # Folder config file 428 | [Dd]esktop.ini 429 | 430 | # Recycle Bin used on file shares 431 | $RECYCLE.BIN/ 432 | 433 | # Windows Installer files 434 | *.cab 435 | *.msi 436 | *.msix 437 | *.msm 438 | *.msp 439 | 440 | # Windows shortcuts 441 | *.lnk 442 | 443 | # JetBrains Rider 444 | .idea/ 445 | *.sln.iml 446 | 447 | ## 448 | ## Visual Studio Code 449 | ## 450 | .vscode/* 451 | !.vscode/settings.json 452 | !.vscode/tasks.json 453 | !.vscode/launch.json 454 | !.vscode/extensions.json 455 | CoverageReport 456 | *.cobertura.xml 457 | coverage -------------------------------------------------------------------------------- /.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}/Source/bin/Debug/net7.0/MinimalApi.dll", 14 | "args": [], 15 | "cwd": "${workspaceFolder}/Source", 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 | } -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "sarif-viewer.connectToGithubCodeScanning": "off" 3 | } -------------------------------------------------------------------------------- /.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}/Source/MinimalApi.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}/Source/MinimalApi.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}/Source/MinimalApi.csproj" 37 | ], 38 | "problemMatcher": "$msCompile" 39 | } 40 | ] 41 | } -------------------------------------------------------------------------------- /MinimalApi.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.30114.105 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MinimalApi", "Source\MinimalApi.csproj", "{7046FE36-5C12-449E-8DF9-287D50A017C5}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MinimalApi.Tests", "Tests\MinimalApi.Tests.csproj", "{77860950-A6AC-4C8F-9E34-F11E72286CFF}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionProperties) = preSolution 12 | HideSolutionNode = FALSE 13 | EndGlobalSection 14 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 15 | Debug|Any CPU = Debug|Any CPU 16 | Debug|x64 = Debug|x64 17 | Debug|x86 = Debug|x86 18 | Release|Any CPU = Release|Any CPU 19 | Release|x64 = Release|x64 20 | Release|x86 = Release|x86 21 | EndGlobalSection 22 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 23 | {7046FE36-5C12-449E-8DF9-287D50A017C5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 24 | {7046FE36-5C12-449E-8DF9-287D50A017C5}.Debug|Any CPU.Build.0 = Debug|Any CPU 25 | {7046FE36-5C12-449E-8DF9-287D50A017C5}.Debug|x64.ActiveCfg = Debug|Any CPU 26 | {7046FE36-5C12-449E-8DF9-287D50A017C5}.Debug|x64.Build.0 = Debug|Any CPU 27 | {7046FE36-5C12-449E-8DF9-287D50A017C5}.Debug|x86.ActiveCfg = Debug|Any CPU 28 | {7046FE36-5C12-449E-8DF9-287D50A017C5}.Debug|x86.Build.0 = Debug|Any CPU 29 | {7046FE36-5C12-449E-8DF9-287D50A017C5}.Release|Any CPU.ActiveCfg = Release|Any CPU 30 | {7046FE36-5C12-449E-8DF9-287D50A017C5}.Release|Any CPU.Build.0 = Release|Any CPU 31 | {7046FE36-5C12-449E-8DF9-287D50A017C5}.Release|x64.ActiveCfg = Release|Any CPU 32 | {7046FE36-5C12-449E-8DF9-287D50A017C5}.Release|x64.Build.0 = Release|Any CPU 33 | {7046FE36-5C12-449E-8DF9-287D50A017C5}.Release|x86.ActiveCfg = Release|Any CPU 34 | {7046FE36-5C12-449E-8DF9-287D50A017C5}.Release|x86.Build.0 = Release|Any CPU 35 | {77860950-A6AC-4C8F-9E34-F11E72286CFF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 36 | {77860950-A6AC-4C8F-9E34-F11E72286CFF}.Debug|Any CPU.Build.0 = Debug|Any CPU 37 | {77860950-A6AC-4C8F-9E34-F11E72286CFF}.Debug|x64.ActiveCfg = Debug|Any CPU 38 | {77860950-A6AC-4C8F-9E34-F11E72286CFF}.Debug|x64.Build.0 = Debug|Any CPU 39 | {77860950-A6AC-4C8F-9E34-F11E72286CFF}.Debug|x86.ActiveCfg = Debug|Any CPU 40 | {77860950-A6AC-4C8F-9E34-F11E72286CFF}.Debug|x86.Build.0 = Debug|Any CPU 41 | {77860950-A6AC-4C8F-9E34-F11E72286CFF}.Release|Any CPU.ActiveCfg = Release|Any CPU 42 | {77860950-A6AC-4C8F-9E34-F11E72286CFF}.Release|Any CPU.Build.0 = Release|Any CPU 43 | {77860950-A6AC-4C8F-9E34-F11E72286CFF}.Release|x64.ActiveCfg = Release|Any CPU 44 | {77860950-A6AC-4C8F-9E34-F11E72286CFF}.Release|x64.Build.0 = Release|Any CPU 45 | {77860950-A6AC-4C8F-9E34-F11E72286CFF}.Release|x86.ActiveCfg = Release|Any CPU 46 | {77860950-A6AC-4C8F-9E34-F11E72286CFF}.Release|x86.Build.0 = Release|Any CPU 47 | EndGlobalSection 48 | EndGlobal 49 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ASP.NET Core 8.0 - Minimal API Example. 2 | 3 | ASP.NET Core 8.0 - Minimal API Example - Todo API implementation using ASP.NET Core Minimal API, Entity Framework Core, Token authentication, Versioning, Unit Testing, Integration Testing and Open API. 4 | 5 | [![Build and Deployment](https://github.com/anuraj/MinimalApi/actions/workflows/main.yml/badge.svg)](https://github.com/anuraj/MinimalApi/actions/workflows/main.yml) 6 | 7 | ## Features 8 | ### November 17, 2023 9 | * Upgraded to .NET 8 10 | 11 | ### September 22, 2023 12 | * Upgraded to .NET 8 RC1 - [More details](https://devblogs.microsoft.com/dotnet/announcing-dotnet-8-rc1/?WT.mc_id=DT-MVP-5002040) 13 | * No other .NET 8 features implemented. 14 | 15 | ### November 29, 2022 16 | * Implemented Rate Limiting support for Web API in .NET 7 - [Learn more about this feature](https://learn.microsoft.com/aspnet/core/performance/rate-limit?view=aspnetcore-7.0&WT.mc_id=DT-MVP-5002040) 17 | * Removed GraphQL support. 18 | 19 | ### November 22, 2022 20 | * Publishing Code coverage results as artifact 21 | 22 | ### November 21, 2022 23 | * DotNet CLI - Container image publish support added - [Learn more about this feature](https://devblogs.microsoft.com/dotnet/announcing-builtin-container-support-for-the-dotnet-sdk/?WT.mc_id=DT-MVP-5002040) 24 | * Modified authentication code to support `dotnet user-jwts`. Removed the `token` endpoint 25 | * How to create token using `dotnet user-jwts`. 26 | * If the dotnet tool not exist, you may need to install it first. 27 | * Execute the command - `dotnet user-jwts create --claim Username=user1 --claim Email=user1@example.com --name user1`. 28 | * This will generate a token and you can use this token in the Swagger / Open API. 29 | 30 | You can find more details here - [Manage JSON Web Tokens in development with dotnet user-jwts](https://learn.microsoft.com/en-us/aspnet/core/security/authentication/jwt-authn?view=aspnetcore-7.0&tabs=windows&WT.mc_id=DT-MVP-5002040) 31 | 32 | ### November 18, 2022 33 | * Moved from .NET 6.0 to .NET 7.0 34 | * Endpoint Filters added - [Learn more about this feature](https://learn.microsoft.com/aspnet/core/fundamentals/minimal-apis/min-api-filters?view=aspnetcore-7.0&WT.mc_id=DT-MVP-5002040) 35 | 36 | ### October 18, 2022 37 | * NuGet packages upgraded to RC. 38 | 39 | ### July 25, 2022 40 | * Route groups Implemented - [Learn more about this feature](https://learn.microsoft.com/aspnet/core/fundamentals/minimal-apis?view=aspnetcore-7.0&WT.mc_id=DT-MVP-5002040#route-groups) 41 | * Code coverage implemented. 42 | 43 | ### July 24, 2022 44 | * Upgraded to .NET 7 - Preview. 45 | * Added Unit Tests (Unit Tests support for Minimal API available in .NET 7) 46 | 47 | ### July 22, 2022 48 | * Implemented Paging. 49 | 50 | ### July 21, 2022 51 | * Validation support using FluentValidation 52 | * Refactoring and fixed all the warnings. 53 | * Graph QL Authentication 54 | 55 | ### December 1, 2021 56 | * Implemented DTO for Input and Output. 57 | * Bug Fix - the /history endpoint was not returning any data. 58 | 59 | ### November 24, 2021 60 | * Token Authentication and Open API changes related to that. 61 | 62 | ### November 14, 2021 63 | * GraphQL Implementation using HotChocolate 64 | - Query 65 | - Mutation 66 | - Subscription 67 | 68 | ### November 11, 2021 69 | * CRUD operations using Minimal API .NET 6.0 and Sql Server 70 | * Health Checks implementation for Minimal APIs 71 | * Open API - Support for Tags 72 | * EF Core new features 73 | - Temporal Tables in Sql Server 74 | - Run migration using EF Bundles 75 | -------------------------------------------------------------------------------- /Source/.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/MinimalApi.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 | } -------------------------------------------------------------------------------- /Source/.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}/MinimalApi.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}/MinimalApi.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}/MinimalApi.csproj" 37 | ], 38 | "problemMatcher": "$msCompile" 39 | } 40 | ] 41 | } -------------------------------------------------------------------------------- /Source/ApiVersionOperationFilter.cs: -------------------------------------------------------------------------------- 1 | using Swashbuckle.AspNetCore.SwaggerGen; 2 | using Microsoft.OpenApi.Any; 3 | 4 | namespace MinimalApi; 5 | 6 | public class ApiVersionOperationFilter : IOperationFilter 7 | { 8 | public void Apply(OpenApiOperation operation, OperationFilterContext context) 9 | { 10 | var actionMetadata = context.ApiDescription.ActionDescriptor.EndpointMetadata; 11 | operation.Parameters ??= new List(); 12 | 13 | var apiVersionMetadata = actionMetadata 14 | .Any(metadataItem => metadataItem is ApiVersionMetadata); 15 | if (apiVersionMetadata) 16 | { 17 | operation.Parameters.Add(new OpenApiParameter 18 | { 19 | Name = "API-Version", 20 | In = ParameterLocation.Header, 21 | Description = "API Version header value", 22 | Schema = new OpenApiSchema 23 | { 24 | Type = "String", 25 | Default = new OpenApiString("1.0") 26 | } 27 | }); 28 | } 29 | } 30 | } -------------------------------------------------------------------------------- /Source/AuthorizationHeaderOperationHeader.cs: -------------------------------------------------------------------------------- 1 | using Swashbuckle.AspNetCore.SwaggerGen; 2 | using Microsoft.AspNetCore.Authorization; 3 | 4 | namespace MinimalApi; 5 | 6 | public class AuthorizationHeaderOperationHeader : IOperationFilter 7 | { 8 | public void Apply(OpenApiOperation operation, OperationFilterContext context) 9 | { 10 | var actionMetadata = context.ApiDescription.ActionDescriptor.EndpointMetadata; 11 | var isAuthorized = actionMetadata.Any(metadataItem => metadataItem is AuthorizeAttribute); 12 | var allowAnonymous = actionMetadata.Any(metadataItem => metadataItem is AllowAnonymousAttribute); 13 | 14 | if (!isAuthorized || allowAnonymous) 15 | { 16 | return; 17 | } 18 | if (operation.Parameters == null) 19 | operation.Parameters = new List(); 20 | 21 | operation.Security = new List(); 22 | 23 | //Add JWT bearer type 24 | operation.Security.Add(new OpenApiSecurityRequirement() { 25 | { 26 | new OpenApiSecurityScheme { 27 | Reference = new OpenApiReference { 28 | Id = "Bearer", 29 | Type = ReferenceType.SecurityScheme 30 | } 31 | }, 32 | new List() 33 | } 34 | } 35 | ); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Source/Data/Migrations/20211111034925_InitialMigrations.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using System; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.EntityFrameworkCore.Infrastructure; 5 | using Microsoft.EntityFrameworkCore.Metadata; 6 | using Microsoft.EntityFrameworkCore.Migrations; 7 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 8 | 9 | #nullable disable 10 | 11 | namespace MinimalApi.Data.Migrations 12 | { 13 | [DbContext(typeof(TodoDbContext))] 14 | [Migration("20211111034925_InitialMigrations")] 15 | partial class InitialMigrations 16 | { 17 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 18 | { 19 | #pragma warning disable 612, 618 20 | modelBuilder 21 | .HasAnnotation("ProductVersion", "6.0.0") 22 | .HasAnnotation("Relational:MaxIdentifierLength", 128); 23 | 24 | SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder, 1L, 1); 25 | 26 | modelBuilder.Entity("TodoItem", b => 27 | { 28 | b.Property("Id") 29 | .ValueGeneratedOnAdd() 30 | .HasColumnType("int"); 31 | 32 | SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id"), 1L, 1); 33 | 34 | b.Property("IsCompleted") 35 | .HasColumnType("bit"); 36 | 37 | b.Property("PeriodEnd") 38 | .ValueGeneratedOnAddOrUpdate() 39 | .HasColumnType("datetime2") 40 | .HasColumnName("PeriodEnd"); 41 | 42 | b.Property("PeriodStart") 43 | .ValueGeneratedOnAddOrUpdate() 44 | .HasColumnType("datetime2") 45 | .HasColumnName("PeriodStart"); 46 | 47 | b.Property("Title") 48 | .HasColumnType("nvarchar(max)"); 49 | 50 | b.HasKey("Id"); 51 | 52 | b.ToTable("TodoItems", (string)null); 53 | 54 | b.ToTable(tb => tb.IsTemporal(ttb => 55 | { 56 | ttb 57 | .HasPeriodStart("PeriodStart") 58 | .HasColumnName("PeriodStart"); 59 | ttb 60 | .HasPeriodEnd("PeriodEnd") 61 | .HasColumnName("PeriodEnd"); 62 | } 63 | )); 64 | }); 65 | #pragma warning restore 612, 618 66 | } 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /Source/Data/Migrations/20211111034925_InitialMigrations.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.EntityFrameworkCore.Migrations; 3 | 4 | #nullable disable 5 | 6 | namespace MinimalApi.Data.Migrations 7 | { 8 | public partial class InitialMigrations : Migration 9 | { 10 | protected override void Up(MigrationBuilder migrationBuilder) 11 | { 12 | migrationBuilder.CreateTable( 13 | name: "TodoItems", 14 | columns: table => new 15 | { 16 | Id = table.Column(type: "int", nullable: false) 17 | .Annotation("SqlServer:Identity", "1, 1"), 18 | Title = table.Column(type: "nvarchar(max)", nullable: true), 19 | IsCompleted = table.Column(type: "bit", nullable: false), 20 | PeriodEnd = table.Column(type: "datetime2", nullable: false) 21 | .Annotation("SqlServer:IsTemporal", true) 22 | .Annotation("SqlServer:TemporalPeriodEndColumnName", "PeriodEnd") 23 | .Annotation("SqlServer:TemporalPeriodStartColumnName", "PeriodStart"), 24 | PeriodStart = table.Column(type: "datetime2", nullable: false) 25 | .Annotation("SqlServer:IsTemporal", true) 26 | .Annotation("SqlServer:TemporalPeriodEndColumnName", "PeriodEnd") 27 | .Annotation("SqlServer:TemporalPeriodStartColumnName", "PeriodStart") 28 | }, 29 | constraints: table => 30 | { 31 | table.PrimaryKey("PK_TodoItems", x => x.Id); 32 | }) 33 | .Annotation("SqlServer:IsTemporal", true) 34 | .Annotation("SqlServer:TemporalHistoryTableName", "TodoItemsHistory") 35 | .Annotation("SqlServer:TemporalHistoryTableSchema", null) 36 | .Annotation("SqlServer:TemporalPeriodEndColumnName", "PeriodEnd") 37 | .Annotation("SqlServer:TemporalPeriodStartColumnName", "PeriodStart"); 38 | } 39 | 40 | protected override void Down(MigrationBuilder migrationBuilder) 41 | { 42 | migrationBuilder.DropTable( 43 | name: "TodoItems") 44 | .Annotation("SqlServer:IsTemporal", true) 45 | .Annotation("SqlServer:TemporalHistoryTableName", "TodoItemsHistory") 46 | .Annotation("SqlServer:TemporalHistoryTableSchema", null) 47 | .Annotation("SqlServer:TemporalPeriodEndColumnName", "PeriodEnd") 48 | .Annotation("SqlServer:TemporalPeriodStartColumnName", "PeriodStart"); 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /Source/Data/Migrations/20211123093642_UserTableAdded.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using System; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.EntityFrameworkCore.Infrastructure; 5 | using Microsoft.EntityFrameworkCore.Metadata; 6 | using Microsoft.EntityFrameworkCore.Migrations; 7 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 8 | 9 | #nullable disable 10 | 11 | namespace MinimalApi.Data.Migrations 12 | { 13 | [DbContext(typeof(TodoDbContext))] 14 | [Migration("20211123093642_UserTableAdded")] 15 | partial class UserTableAdded 16 | { 17 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 18 | { 19 | #pragma warning disable 612, 618 20 | modelBuilder 21 | .HasAnnotation("ProductVersion", "6.0.0") 22 | .HasAnnotation("Relational:MaxIdentifierLength", 128); 23 | 24 | SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder, 1L, 1); 25 | 26 | modelBuilder.Entity("TodoItem", b => 27 | { 28 | b.Property("Id") 29 | .ValueGeneratedOnAdd() 30 | .HasColumnType("int"); 31 | 32 | SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id"), 1L, 1); 33 | 34 | b.Property("CreatedOn") 35 | .HasColumnType("datetime2"); 36 | 37 | b.Property("IsCompleted") 38 | .HasColumnType("bit"); 39 | 40 | b.Property("PeriodEnd") 41 | .ValueGeneratedOnAddOrUpdate() 42 | .HasColumnType("datetime2") 43 | .HasColumnName("PeriodEnd"); 44 | 45 | b.Property("PeriodStart") 46 | .ValueGeneratedOnAddOrUpdate() 47 | .HasColumnType("datetime2") 48 | .HasColumnName("PeriodStart"); 49 | 50 | b.Property("Title") 51 | .IsRequired() 52 | .HasColumnType("nvarchar(max)"); 53 | 54 | b.Property("UserId") 55 | .HasColumnType("int"); 56 | 57 | b.HasKey("Id"); 58 | 59 | b.HasIndex("UserId"); 60 | 61 | b.ToTable("TodoItems", (string)null); 62 | 63 | b.ToTable(tb => tb.IsTemporal(ttb => 64 | { 65 | ttb 66 | .HasPeriodStart("PeriodStart") 67 | .HasColumnName("PeriodStart"); 68 | ttb 69 | .HasPeriodEnd("PeriodEnd") 70 | .HasColumnName("PeriodEnd"); 71 | } 72 | )); 73 | 74 | b.HasData( 75 | new 76 | { 77 | Id = 1, 78 | CreatedOn = new DateTime(2021, 11, 23, 9, 36, 41, 976, DateTimeKind.Utc).AddTicks(8786), 79 | IsCompleted = false, 80 | Title = "Todo Item 1", 81 | UserId = 1 82 | }); 83 | }); 84 | 85 | modelBuilder.Entity("User", b => 86 | { 87 | b.Property("Id") 88 | .ValueGeneratedOnAdd() 89 | .HasColumnType("int"); 90 | 91 | SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id"), 1L, 1); 92 | 93 | b.Property("CreatedOn") 94 | .HasColumnType("datetime2"); 95 | 96 | b.Property("Email") 97 | .IsRequired() 98 | .HasColumnType("nvarchar(max)"); 99 | 100 | b.Property("Password") 101 | .IsRequired() 102 | .HasColumnType("nvarchar(max)"); 103 | 104 | b.Property("Username") 105 | .IsRequired() 106 | .HasColumnType("nvarchar(max)"); 107 | 108 | b.HasKey("Id"); 109 | 110 | b.ToTable("Users"); 111 | 112 | b.HasData( 113 | new 114 | { 115 | Id = 1, 116 | CreatedOn = new DateTime(2021, 11, 23, 9, 36, 41, 976, DateTimeKind.Utc).AddTicks(8657), 117 | Email = "admin@example.com", 118 | Password = "admin", 119 | Username = "admin" 120 | }); 121 | }); 122 | 123 | modelBuilder.Entity("TodoItem", b => 124 | { 125 | b.HasOne("User", "User") 126 | .WithMany("Todos") 127 | .HasForeignKey("UserId") 128 | .OnDelete(DeleteBehavior.Cascade) 129 | .IsRequired(); 130 | 131 | b.Navigation("User"); 132 | }); 133 | 134 | modelBuilder.Entity("User", b => 135 | { 136 | b.Navigation("Todos"); 137 | }); 138 | #pragma warning restore 612, 618 139 | } 140 | } 141 | } 142 | -------------------------------------------------------------------------------- /Source/Data/Migrations/20211123093642_UserTableAdded.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.EntityFrameworkCore.Migrations; 3 | 4 | #nullable disable 5 | 6 | namespace MinimalApi.Data.Migrations 7 | { 8 | public partial class UserTableAdded : Migration 9 | { 10 | protected override void Up(MigrationBuilder migrationBuilder) 11 | { 12 | migrationBuilder.AlterColumn( 13 | name: "Title", 14 | table: "TodoItems", 15 | type: "nvarchar(max)", 16 | nullable: false, 17 | defaultValue: "", 18 | oldClrType: typeof(string), 19 | oldType: "nvarchar(max)", 20 | oldNullable: true); 21 | 22 | migrationBuilder.AddColumn( 23 | name: "CreatedOn", 24 | table: "TodoItems", 25 | type: "datetime2", 26 | nullable: false, 27 | defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)); 28 | 29 | migrationBuilder.AddColumn( 30 | name: "UserId", 31 | table: "TodoItems", 32 | type: "int", 33 | nullable: false, 34 | defaultValue: 0); 35 | 36 | migrationBuilder.CreateTable( 37 | name: "Users", 38 | columns: table => new 39 | { 40 | Id = table.Column(type: "int", nullable: false) 41 | .Annotation("SqlServer:Identity", "1, 1"), 42 | Username = table.Column(type: "nvarchar(max)", nullable: false), 43 | Password = table.Column(type: "nvarchar(max)", nullable: false), 44 | CreatedOn = table.Column(type: "datetime2", nullable: false), 45 | Email = table.Column(type: "nvarchar(max)", nullable: false) 46 | }, 47 | constraints: table => 48 | { 49 | table.PrimaryKey("PK_Users", x => x.Id); 50 | }); 51 | 52 | migrationBuilder.InsertData( 53 | table: "Users", 54 | columns: new[] { "Id", "CreatedOn", "Email", "Password", "Username" }, 55 | values: new object[] { 1, new DateTime(2021, 11, 23, 9, 36, 41, 976, DateTimeKind.Utc).AddTicks(8657), "admin@example.com", "admin", "admin" }); 56 | 57 | migrationBuilder.InsertData( 58 | table: "TodoItems", 59 | columns: new[] { "Id", "CreatedOn", "IsCompleted", "Title", "UserId" }, 60 | values: new object[] { 1, new DateTime(2021, 11, 23, 9, 36, 41, 976, DateTimeKind.Utc).AddTicks(8786), false, "Todo Item 1", 1 }); 61 | 62 | migrationBuilder.CreateIndex( 63 | name: "IX_TodoItems_UserId", 64 | table: "TodoItems", 65 | column: "UserId"); 66 | 67 | migrationBuilder.AddForeignKey( 68 | name: "FK_TodoItems_Users_UserId", 69 | table: "TodoItems", 70 | column: "UserId", 71 | principalTable: "Users", 72 | principalColumn: "Id", 73 | onDelete: ReferentialAction.Cascade); 74 | } 75 | 76 | protected override void Down(MigrationBuilder migrationBuilder) 77 | { 78 | migrationBuilder.DropForeignKey( 79 | name: "FK_TodoItems_Users_UserId", 80 | table: "TodoItems"); 81 | 82 | migrationBuilder.DropTable( 83 | name: "Users"); 84 | 85 | migrationBuilder.DropIndex( 86 | name: "IX_TodoItems_UserId", 87 | table: "TodoItems"); 88 | 89 | migrationBuilder.DeleteData( 90 | table: "TodoItems", 91 | keyColumn: "Id", 92 | keyValue: 1); 93 | 94 | migrationBuilder.DropColumn( 95 | name: "CreatedOn", 96 | table: "TodoItems") 97 | .Annotation("SqlServer:IsTemporal", true) 98 | .Annotation("SqlServer:TemporalHistoryTableName", "TodoItemsHistory") 99 | .Annotation("SqlServer:TemporalHistoryTableSchema", null); 100 | 101 | migrationBuilder.DropColumn( 102 | name: "UserId", 103 | table: "TodoItems") 104 | .Annotation("SqlServer:IsTemporal", true) 105 | .Annotation("SqlServer:TemporalHistoryTableName", "TodoItemsHistory") 106 | .Annotation("SqlServer:TemporalHistoryTableSchema", null); 107 | 108 | migrationBuilder.AlterColumn( 109 | name: "Title", 110 | table: "TodoItems", 111 | type: "nvarchar(max)", 112 | nullable: true, 113 | oldClrType: typeof(string), 114 | oldType: "nvarchar(max)"); 115 | } 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /Source/Data/Migrations/20211201054707_UsersTableSetAsTemporal.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using System; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.EntityFrameworkCore.Infrastructure; 5 | using Microsoft.EntityFrameworkCore.Metadata; 6 | using Microsoft.EntityFrameworkCore.Migrations; 7 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 8 | 9 | #nullable disable 10 | 11 | namespace MinimalApi.Data.Migrations 12 | { 13 | [DbContext(typeof(TodoDbContext))] 14 | [Migration("20211201054707_UsersTableSetAsTemporal")] 15 | partial class UsersTableSetAsTemporal 16 | { 17 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 18 | { 19 | #pragma warning disable 612, 618 20 | modelBuilder 21 | .HasAnnotation("ProductVersion", "6.0.0") 22 | .HasAnnotation("Relational:MaxIdentifierLength", 128); 23 | 24 | SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder, 1L, 1); 25 | 26 | modelBuilder.Entity("TodoItem", b => 27 | { 28 | b.Property("Id") 29 | .ValueGeneratedOnAdd() 30 | .HasColumnType("int"); 31 | 32 | SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id"), 1L, 1); 33 | 34 | b.Property("CreatedOn") 35 | .HasColumnType("datetime2"); 36 | 37 | b.Property("IsCompleted") 38 | .HasColumnType("bit"); 39 | 40 | b.Property("PeriodEnd") 41 | .ValueGeneratedOnAddOrUpdate() 42 | .HasColumnType("datetime2") 43 | .HasColumnName("PeriodEnd"); 44 | 45 | b.Property("PeriodStart") 46 | .ValueGeneratedOnAddOrUpdate() 47 | .HasColumnType("datetime2") 48 | .HasColumnName("PeriodStart"); 49 | 50 | b.Property("Title") 51 | .IsRequired() 52 | .HasColumnType("nvarchar(max)"); 53 | 54 | b.Property("UserId") 55 | .HasColumnType("int"); 56 | 57 | b.HasKey("Id"); 58 | 59 | b.HasIndex("UserId"); 60 | 61 | b.ToTable("TodoItems", (string)null); 62 | 63 | b.ToTable(tb => tb.IsTemporal(ttb => 64 | { 65 | ttb 66 | .HasPeriodStart("PeriodStart") 67 | .HasColumnName("PeriodStart"); 68 | ttb 69 | .HasPeriodEnd("PeriodEnd") 70 | .HasColumnName("PeriodEnd"); 71 | } 72 | )); 73 | 74 | b.HasData( 75 | new 76 | { 77 | Id = 1, 78 | CreatedOn = new DateTime(2021, 12, 1, 5, 47, 6, 969, DateTimeKind.Utc).AddTicks(6540), 79 | IsCompleted = false, 80 | Title = "Todo Item 1", 81 | UserId = 1 82 | }); 83 | }); 84 | 85 | modelBuilder.Entity("User", b => 86 | { 87 | b.Property("Id") 88 | .ValueGeneratedOnAdd() 89 | .HasColumnType("int"); 90 | 91 | SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id"), 1L, 1); 92 | 93 | b.Property("CreatedOn") 94 | .HasColumnType("datetime2"); 95 | 96 | b.Property("Email") 97 | .IsRequired() 98 | .HasColumnType("nvarchar(max)"); 99 | 100 | b.Property("Password") 101 | .IsRequired() 102 | .HasColumnType("nvarchar(max)"); 103 | 104 | b.Property("PeriodEnd") 105 | .ValueGeneratedOnAddOrUpdate() 106 | .HasColumnType("datetime2") 107 | .HasColumnName("PeriodEnd"); 108 | 109 | b.Property("PeriodStart") 110 | .ValueGeneratedOnAddOrUpdate() 111 | .HasColumnType("datetime2") 112 | .HasColumnName("PeriodStart"); 113 | 114 | b.Property("Username") 115 | .IsRequired() 116 | .HasColumnType("nvarchar(max)"); 117 | 118 | b.HasKey("Id"); 119 | 120 | b.ToTable("Users", (string)null); 121 | 122 | b.ToTable(tb => tb.IsTemporal(ttb => 123 | { 124 | ttb 125 | .HasPeriodStart("PeriodStart") 126 | .HasColumnName("PeriodStart"); 127 | ttb 128 | .HasPeriodEnd("PeriodEnd") 129 | .HasColumnName("PeriodEnd"); 130 | } 131 | )); 132 | 133 | b.HasData( 134 | new 135 | { 136 | Id = 1, 137 | CreatedOn = new DateTime(2021, 12, 1, 5, 47, 6, 969, DateTimeKind.Utc).AddTicks(6423), 138 | Email = "admin@example.com", 139 | Password = "admin", 140 | Username = "admin" 141 | }); 142 | }); 143 | 144 | modelBuilder.Entity("TodoItem", b => 145 | { 146 | b.HasOne("User", "User") 147 | .WithMany("Todos") 148 | .HasForeignKey("UserId") 149 | .OnDelete(DeleteBehavior.Cascade) 150 | .IsRequired(); 151 | 152 | b.Navigation("User"); 153 | }); 154 | 155 | modelBuilder.Entity("User", b => 156 | { 157 | b.Navigation("Todos"); 158 | }); 159 | #pragma warning restore 612, 618 160 | } 161 | } 162 | } 163 | -------------------------------------------------------------------------------- /Source/Data/Migrations/20211201054707_UsersTableSetAsTemporal.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.EntityFrameworkCore.Migrations; 3 | 4 | #nullable disable 5 | 6 | namespace MinimalApi.Data.Migrations 7 | { 8 | public partial class UsersTableSetAsTemporal : Migration 9 | { 10 | protected override void Up(MigrationBuilder migrationBuilder) 11 | { 12 | migrationBuilder.AlterTable( 13 | name: "Users") 14 | .Annotation("SqlServer:IsTemporal", true) 15 | .Annotation("SqlServer:TemporalHistoryTableName", "UsersHistory") 16 | .Annotation("SqlServer:TemporalHistoryTableSchema", null) 17 | .Annotation("SqlServer:TemporalPeriodEndColumnName", "PeriodEnd") 18 | .Annotation("SqlServer:TemporalPeriodStartColumnName", "PeriodStart"); 19 | 20 | migrationBuilder.AddColumn( 21 | name: "PeriodEnd", 22 | table: "Users", 23 | type: "datetime2", 24 | nullable: false, 25 | defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)) 26 | .Annotation("SqlServer:IsTemporal", true) 27 | .Annotation("SqlServer:TemporalPeriodEndColumnName", "PeriodEnd") 28 | .Annotation("SqlServer:TemporalPeriodStartColumnName", "PeriodStart"); 29 | 30 | migrationBuilder.AddColumn( 31 | name: "PeriodStart", 32 | table: "Users", 33 | type: "datetime2", 34 | nullable: false, 35 | defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)) 36 | .Annotation("SqlServer:IsTemporal", true) 37 | .Annotation("SqlServer:TemporalPeriodEndColumnName", "PeriodEnd") 38 | .Annotation("SqlServer:TemporalPeriodStartColumnName", "PeriodStart"); 39 | 40 | migrationBuilder.UpdateData( 41 | table: "TodoItems", 42 | keyColumn: "Id", 43 | keyValue: 1, 44 | column: "CreatedOn", 45 | value: new DateTime(2021, 12, 1, 5, 47, 6, 969, DateTimeKind.Utc).AddTicks(6540)); 46 | 47 | migrationBuilder.UpdateData( 48 | table: "Users", 49 | keyColumn: "Id", 50 | keyValue: 1, 51 | column: "CreatedOn", 52 | value: new DateTime(2021, 12, 1, 5, 47, 6, 969, DateTimeKind.Utc).AddTicks(6423)); 53 | } 54 | 55 | protected override void Down(MigrationBuilder migrationBuilder) 56 | { 57 | migrationBuilder.DropColumn( 58 | name: "PeriodEnd", 59 | table: "Users") 60 | .Annotation("SqlServer:IsTemporal", true) 61 | .Annotation("SqlServer:TemporalHistoryTableName", "UsersHistory") 62 | .Annotation("SqlServer:TemporalHistoryTableSchema", null) 63 | .Annotation("SqlServer:TemporalPeriodEndColumnName", "PeriodEnd") 64 | .Annotation("SqlServer:TemporalPeriodStartColumnName", "PeriodStart"); 65 | 66 | migrationBuilder.DropColumn( 67 | name: "PeriodStart", 68 | table: "Users") 69 | .Annotation("SqlServer:IsTemporal", true) 70 | .Annotation("SqlServer:TemporalHistoryTableName", "UsersHistory") 71 | .Annotation("SqlServer:TemporalHistoryTableSchema", null) 72 | .Annotation("SqlServer:TemporalPeriodEndColumnName", "PeriodEnd") 73 | .Annotation("SqlServer:TemporalPeriodStartColumnName", "PeriodStart"); 74 | 75 | migrationBuilder.AlterTable( 76 | name: "Users") 77 | .OldAnnotation("SqlServer:IsTemporal", true) 78 | .OldAnnotation("SqlServer:TemporalHistoryTableName", "UsersHistory") 79 | .OldAnnotation("SqlServer:TemporalHistoryTableSchema", null) 80 | .OldAnnotation("SqlServer:TemporalPeriodEndColumnName", "PeriodEnd") 81 | .OldAnnotation("SqlServer:TemporalPeriodStartColumnName", "PeriodStart"); 82 | 83 | migrationBuilder.UpdateData( 84 | table: "TodoItems", 85 | keyColumn: "Id", 86 | keyValue: 1, 87 | column: "CreatedOn", 88 | value: new DateTime(2021, 11, 23, 9, 36, 41, 976, DateTimeKind.Utc).AddTicks(8786)); 89 | 90 | migrationBuilder.UpdateData( 91 | table: "Users", 92 | keyColumn: "Id", 93 | keyValue: 1, 94 | column: "CreatedOn", 95 | value: new DateTime(2021, 11, 23, 9, 36, 41, 976, DateTimeKind.Utc).AddTicks(8657)); 96 | } 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /Source/Data/Migrations/TodoDbContextModelSnapshot.cs: -------------------------------------------------------------------------------- 1 | // 2 | using System; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.EntityFrameworkCore.Infrastructure; 5 | using Microsoft.EntityFrameworkCore.Metadata; 6 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 7 | 8 | #nullable disable 9 | 10 | namespace MinimalApi.Data.Migrations 11 | { 12 | [DbContext(typeof(TodoDbContext))] 13 | partial class TodoDbContextModelSnapshot : ModelSnapshot 14 | { 15 | protected override void BuildModel(ModelBuilder modelBuilder) 16 | { 17 | #pragma warning disable 612, 618 18 | modelBuilder 19 | .HasAnnotation("ProductVersion", "6.0.0") 20 | .HasAnnotation("Relational:MaxIdentifierLength", 128); 21 | 22 | SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder, 1L, 1); 23 | 24 | modelBuilder.Entity("TodoItem", b => 25 | { 26 | b.Property("Id") 27 | .ValueGeneratedOnAdd() 28 | .HasColumnType("int"); 29 | 30 | SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id"), 1L, 1); 31 | 32 | b.Property("CreatedOn") 33 | .HasColumnType("datetime2"); 34 | 35 | b.Property("IsCompleted") 36 | .HasColumnType("bit"); 37 | 38 | b.Property("PeriodEnd") 39 | .ValueGeneratedOnAddOrUpdate() 40 | .HasColumnType("datetime2") 41 | .HasColumnName("PeriodEnd"); 42 | 43 | b.Property("PeriodStart") 44 | .ValueGeneratedOnAddOrUpdate() 45 | .HasColumnType("datetime2") 46 | .HasColumnName("PeriodStart"); 47 | 48 | b.Property("Title") 49 | .IsRequired() 50 | .HasColumnType("nvarchar(max)"); 51 | 52 | b.Property("UserId") 53 | .HasColumnType("int"); 54 | 55 | b.HasKey("Id"); 56 | 57 | b.HasIndex("UserId"); 58 | 59 | b.ToTable("TodoItems", (string)null); 60 | 61 | b.ToTable(tb => tb.IsTemporal(ttb => 62 | { 63 | ttb 64 | .HasPeriodStart("PeriodStart") 65 | .HasColumnName("PeriodStart"); 66 | ttb 67 | .HasPeriodEnd("PeriodEnd") 68 | .HasColumnName("PeriodEnd"); 69 | } 70 | )); 71 | 72 | b.HasData( 73 | new 74 | { 75 | Id = 1, 76 | CreatedOn = new DateTime(2021, 12, 1, 5, 47, 6, 969, DateTimeKind.Utc).AddTicks(6540), 77 | IsCompleted = false, 78 | Title = "Todo Item 1", 79 | UserId = 1 80 | }); 81 | }); 82 | 83 | modelBuilder.Entity("User", b => 84 | { 85 | b.Property("Id") 86 | .ValueGeneratedOnAdd() 87 | .HasColumnType("int"); 88 | 89 | SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id"), 1L, 1); 90 | 91 | b.Property("CreatedOn") 92 | .HasColumnType("datetime2"); 93 | 94 | b.Property("Email") 95 | .IsRequired() 96 | .HasColumnType("nvarchar(max)"); 97 | 98 | b.Property("Password") 99 | .IsRequired() 100 | .HasColumnType("nvarchar(max)"); 101 | 102 | b.Property("PeriodEnd") 103 | .ValueGeneratedOnAddOrUpdate() 104 | .HasColumnType("datetime2") 105 | .HasColumnName("PeriodEnd"); 106 | 107 | b.Property("PeriodStart") 108 | .ValueGeneratedOnAddOrUpdate() 109 | .HasColumnType("datetime2") 110 | .HasColumnName("PeriodStart"); 111 | 112 | b.Property("Username") 113 | .IsRequired() 114 | .HasColumnType("nvarchar(max)"); 115 | 116 | b.HasKey("Id"); 117 | 118 | b.ToTable("Users", (string)null); 119 | 120 | b.ToTable(tb => tb.IsTemporal(ttb => 121 | { 122 | ttb 123 | .HasPeriodStart("PeriodStart") 124 | .HasColumnName("PeriodStart"); 125 | ttb 126 | .HasPeriodEnd("PeriodEnd") 127 | .HasColumnName("PeriodEnd"); 128 | } 129 | )); 130 | 131 | b.HasData( 132 | new 133 | { 134 | Id = 1, 135 | CreatedOn = new DateTime(2021, 12, 1, 5, 47, 6, 969, DateTimeKind.Utc).AddTicks(6423), 136 | Email = "admin@example.com", 137 | Password = "admin", 138 | Username = "admin" 139 | }); 140 | }); 141 | 142 | modelBuilder.Entity("TodoItem", b => 143 | { 144 | b.HasOne("User", "User") 145 | .WithMany("Todos") 146 | .HasForeignKey("UserId") 147 | .OnDelete(DeleteBehavior.Cascade) 148 | .IsRequired(); 149 | 150 | b.Navigation("User"); 151 | }); 152 | 153 | modelBuilder.Entity("User", b => 154 | { 155 | b.Navigation("Todos"); 156 | }); 157 | #pragma warning restore 612, 618 158 | } 159 | } 160 | } 161 | -------------------------------------------------------------------------------- /Source/Data/TodoDbContext.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Cryptography.KeyDerivation; 2 | 3 | using System.Security.Cryptography; 4 | 5 | namespace MinimalApi.Data; 6 | 7 | public class TodoDbContext(DbContextOptions options) : DbContext(options) 8 | { 9 | protected override void OnModelCreating(ModelBuilder modelBuilder) 10 | { 11 | modelBuilder.Entity().ToTable("TodoItems", t => t.IsTemporal()); 12 | modelBuilder.Entity().ToTable("Users", u => u.IsTemporal()); 13 | for (var i = 1; i <= 20; i++) 14 | { 15 | byte[] salt = RandomNumberGenerator.GetBytes(128 / 8); 16 | string hashed = Convert.ToBase64String(KeyDerivation.Pbkdf2( 17 | password: $"secret-{i}", 18 | salt: salt, 19 | prf: KeyDerivationPrf.HMACSHA256, 20 | iterationCount: 100000, 21 | numBytesRequested: 256 / 8)); 22 | 23 | modelBuilder.Entity().HasData(new User 24 | { 25 | Id = i, 26 | Username = $"user{i}", 27 | Password = hashed, 28 | Email = $"user{i}@example.com", 29 | CreatedOn = DateTime.UtcNow, 30 | Salt = Convert.ToBase64String(salt), 31 | PermitLimit = 60, 32 | RateLimitWindowInMinutes = 5 33 | }); 34 | } 35 | 36 | for (var i = 1; i <= 20; i++) 37 | { 38 | modelBuilder.Entity().HasData(new TodoItem 39 | { 40 | Id = i, 41 | Title = $"Todo Item {i}", 42 | IsCompleted = false, 43 | CreatedOn = DateTime.UtcNow, 44 | UserId = 1 45 | }); 46 | } 47 | } 48 | 49 | public DbSet TodoItems => Set(); 50 | public DbSet Users => Set(); 51 | } 52 | -------------------------------------------------------------------------------- /Source/MinimalApi.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net8.0 5 | enable 6 | enable 7 | c863d8a7-6953-45aa-baa6-3b932debfdd0 8 | ghcr.io/anuraj/minimalapi 9 | latest 10 | $(BUILD_VERSION) 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | runtime; build; native; contentfiles; analyzers; buildtransitive 21 | all 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /Source/Models/TodoItem.cs: -------------------------------------------------------------------------------- 1 |  2 | using System.ComponentModel.DataAnnotations; 3 | namespace MinimalApi.Models; 4 | 5 | public class TodoItem 6 | { 7 | public int Id { get; set; } 8 | [Required] 9 | public string? Title { get; set; } 10 | public bool IsCompleted { get; set; } 11 | public User User { get; set; } = null!; 12 | public int UserId { get; set; } 13 | public DateTime CreatedOn { get; set; } 14 | } 15 | 16 | -------------------------------------------------------------------------------- /Source/Models/TodoItemAudit.cs: -------------------------------------------------------------------------------- 1 | namespace MinimalApi.Models; 2 | public class TodoItemAudit 3 | { 4 | public string? Title { get; set; } 5 | public bool IsCompleted { get; set; } 6 | public DateTime PeriodStart { get; set; } 7 | public DateTime PeriodEnd { get; set; } 8 | } 9 | -------------------------------------------------------------------------------- /Source/Models/User.cs: -------------------------------------------------------------------------------- 1 |  2 | using System.ComponentModel.DataAnnotations; 3 | namespace MinimalApi.Models; 4 | public class User 5 | { 6 | public int Id { get; set; } 7 | [Required] 8 | public string? Username { get; set; } 9 | [Required] 10 | public string? Password { get; set; } 11 | public DateTime CreatedOn { get; set; } 12 | public string? Email { get; set; } 13 | public ICollection? Todos { get; set; } 14 | public string? Salt { get; set; } 15 | public int RateLimitWindowInMinutes { get; set; } = 5; 16 | public int PermitLimit { get; set; } = 60; 17 | } 18 | -------------------------------------------------------------------------------- /Source/Program.cs: -------------------------------------------------------------------------------- 1 | 2 | 3 | var builder = WebApplication.CreateBuilder(args); 4 | var jwtPolicyName = "jwt"; 5 | 6 | builder.Services.AddRateLimiter(limiterOptions => 7 | { 8 | limiterOptions.RejectionStatusCode = StatusCodes.Status429TooManyRequests; 9 | limiterOptions.OnRejected = (context, cancellationToken) => 10 | { 11 | context.HttpContext.Response.StatusCode = StatusCodes.Status429TooManyRequests; 12 | context.HttpContext.RequestServices.GetService()? 13 | .CreateLogger("Microsoft.AspNetCore.RateLimitingMiddleware") 14 | .LogWarning("OnRejected: {GetUserEndPoint}", GetUserEndPoint(context.HttpContext)); 15 | 16 | return new ValueTask(); 17 | }; 18 | 19 | limiterOptions.AddPolicy(policyName: jwtPolicyName, partitioner: httpContext => 20 | { 21 | var tokenValue = string.Empty; 22 | if (AuthenticationHeaderValue.TryParse(httpContext.Request.Headers["Authorization"], out var authHeader)) 23 | { 24 | tokenValue = authHeader.Parameter; 25 | } 26 | 27 | var email = string.Empty; 28 | var rateLimitWindowInMinutes = 5; 29 | var permitLimitAuthorized = 60; 30 | var permitLimitAnonymous = 30; 31 | if (!string.IsNullOrEmpty(tokenValue)) 32 | { 33 | var handler = new JwtSecurityTokenHandler(); 34 | var token = handler.ReadJwtToken(tokenValue); 35 | email= token.Claims.First(claim => claim.Type == "Email").Value; 36 | var dbContext = httpContext.RequestServices.GetRequiredService(); 37 | var user = dbContext.Users.FirstOrDefault(u => u.Email == email); 38 | if (user != null) 39 | { 40 | permitLimitAuthorized = user.PermitLimit; 41 | rateLimitWindowInMinutes = user.RateLimitWindowInMinutes; 42 | } 43 | } 44 | 45 | return RateLimitPartition.GetFixedWindowLimiter(email, _ => new FixedWindowRateLimiterOptions() 46 | { 47 | PermitLimit = string.IsNullOrEmpty(email) ? permitLimitAnonymous : permitLimitAuthorized, 48 | Window = TimeSpan.FromMinutes(rateLimitWindowInMinutes), 49 | QueueLimit = 0 50 | }); 51 | }); 52 | }); 53 | 54 | static string GetUserEndPoint(HttpContext context) 55 | { 56 | var tokenValue = string.Empty; 57 | if (AuthenticationHeaderValue.TryParse(context.Request.Headers["Authorization"], out var authHeader)) 58 | { 59 | tokenValue = authHeader.Parameter; 60 | } 61 | var email = ""; 62 | if (!string.IsNullOrEmpty(tokenValue)) 63 | { 64 | var handler = new JwtSecurityTokenHandler(); 65 | var token = handler.ReadJwtToken(tokenValue); 66 | email = token.Claims.First(claim => claim.Type == "Email").Value; 67 | } 68 | 69 | return $"User {email ?? "Anonymous"} endpoint:{context.Request.Path}" 70 | + $" {context.Connection.RemoteIpAddress}"; 71 | } 72 | 73 | 74 | builder.WebHost.UseKestrel(options => options.AddServerHeader = false); 75 | builder.Services.AddHttpContextAccessor(); 76 | 77 | builder.Services.AddApiVersioning(options => 78 | { 79 | options.DefaultApiVersion = new ApiVersion(1, 0); 80 | options.ReportApiVersions = true; 81 | options.AssumeDefaultVersionWhenUnspecified = true; 82 | options.ApiVersionReader = new HeaderApiVersionReader("api-version"); 83 | }); 84 | 85 | builder.Services.AddAuthorization(); 86 | builder.Services.AddAuthentication("Bearer").AddJwtBearer(); 87 | builder.Services.AddDbContextFactory(options => options.UseInMemoryDatabase($"MinimalApiDb-{Guid.NewGuid()}")); 88 | 89 | builder.Services.AddEndpointsApiExplorer(); 90 | builder.Services.AddSwaggerGen(setup => 91 | { 92 | setup.SwaggerDoc("v1", new OpenApiInfo() 93 | { 94 | Description = "ASP.NET Core 8.0 - Minimal API Example - Todo API implementation using ASP.NET Core Minimal API," + 95 | "Entity Framework Core, Token authentication, Versioning, Unit Testing and Open API.", 96 | Title = "Todo Api", 97 | Version = "v1", 98 | Contact = new OpenApiContact() 99 | { 100 | Name = "anuraj", 101 | Url = new Uri("https://dotnetthoughts.net") 102 | } 103 | }); 104 | 105 | setup.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme 106 | { 107 | Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"", 108 | Name = "Authorization", 109 | In = ParameterLocation.Header, 110 | Type = SecuritySchemeType.Http, 111 | Scheme = "Bearer" 112 | }); 113 | 114 | setup.OperationFilter(); 115 | setup.OperationFilter(); 116 | }); 117 | 118 | builder.Services.AddDatabaseDeveloperPageExceptionFilter(); 119 | builder.Services.AddHealthChecks().AddDbContextCheck(); 120 | 121 | builder.Services.AddScoped, TodoItemInputValidator>(); 122 | builder.Services.AddScoped, UserInputValidator>(); 123 | 124 | var app = builder.Build(); 125 | 126 | if (app.Environment.IsDevelopment()) 127 | { 128 | app.UseDeveloperExceptionPage(); 129 | } 130 | 131 | var versionSet = app.NewApiVersionSet() 132 | .HasApiVersion(new ApiVersion(1, 0)) 133 | .HasApiVersion(new ApiVersion(2, 0)) 134 | .ReportApiVersions() 135 | .Build(); 136 | 137 | app.UseSwagger(); 138 | 139 | app.UseSwaggerUI(c => 140 | { 141 | c.SwaggerEndpoint("/swagger/v1/swagger.json", "Todo Api v1"); 142 | }); 143 | 144 | app.UseWebSockets(); 145 | 146 | var scope = app.Services.CreateScope(); 147 | var databaseContext = scope.ServiceProvider.GetService(); 148 | if (databaseContext != null) 149 | { 150 | databaseContext.Database.EnsureCreated(); 151 | } 152 | 153 | app.MapGroup("/todoitems") 154 | .MapApiEndpoints() 155 | .WithTags("Todo Items") 156 | .RequireAuthorization() 157 | .RequireRateLimiting(jwtPolicyName) 158 | .WithOpenApi() 159 | .WithMetadata() 160 | .WithApiVersionSet(versionSet) 161 | .AddEndpointFilter(async (efiContext, next) => 162 | { 163 | var stopwatch = Stopwatch.StartNew(); 164 | var result = await next(efiContext); 165 | stopwatch.Stop(); 166 | var elapsed = stopwatch.ElapsedMilliseconds; 167 | var response = efiContext.HttpContext.Response; 168 | response.Headers.TryAdd("X-Response-Time", $"{elapsed} milliseconds"); 169 | return result; 170 | }); 171 | 172 | app.MapGet("/health", async (HealthCheckService healthCheckService) => 173 | { 174 | var report = await healthCheckService.CheckHealthAsync(); 175 | return report.Status == HealthStatus.Healthy ? 176 | Results.Ok(report) : Results.StatusCode(StatusCodes.Status503ServiceUnavailable); 177 | }).WithOpenApi() 178 | .WithTags(new[] { "Health" }) 179 | .RequireRateLimiting(jwtPolicyName) 180 | .Produces(200) 181 | .ProducesProblem(503) 182 | .Produces(429); 183 | 184 | app.UseRouting(); 185 | app.UseRateLimiter(); 186 | app.UseAuthentication(); 187 | app.UseAuthorization(); 188 | 189 | app.Run(); 190 | 191 | //For integration testing 192 | public partial class Program { } -------------------------------------------------------------------------------- /Source/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:21244", 8 | "sslPort": 44373 9 | } 10 | }, 11 | "profiles": { 12 | "MinimalApi": { 13 | "commandName": "Project", 14 | "dotnetRunMessages": true, 15 | "launchBrowser": true, 16 | "launchUrl": "swagger", 17 | "applicationUrl": "https://localhost:5001;http://localhost:5000", 18 | "environmentVariables": { 19 | "ASPNETCORE_ENVIRONMENT": "Development" 20 | } 21 | }, 22 | "IIS Express": { 23 | "commandName": "IISExpress", 24 | "launchBrowser": true, 25 | "launchUrl": "swagger", 26 | "environmentVariables": { 27 | "ASPNETCORE_ENVIRONMENT": "Development" 28 | } 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Source/TodoApi.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | 3 | namespace MinimalApi; 4 | 5 | public static class TodoApi 6 | { 7 | public static RouteGroupBuilder MapApiEndpoints(this RouteGroupBuilder groups) 8 | { 9 | groups.MapGet("/", GetAllTodoItems).Produces(200, typeof(PagedResults)).ProducesProblem(401).Produces(429); 10 | groups.MapGet("/{id}", GetTodoItemById).Produces(200, typeof(TodoItemOutput)).ProducesProblem(401).Produces(429); 11 | groups.MapPost("/", CreateTodoItem).Accepts("application/json").Produces(201).ProducesProblem(401).ProducesProblem(400).Produces(429); 12 | groups.MapPut("/{id}", UpdateTodoItem).Accepts("application/json").Produces(201).ProducesProblem(404).ProducesProblem(401).Produces(429); 13 | groups.MapDelete("/{id}", DeleteTodoItem).Produces(204).ProducesProblem(404).ProducesProblem(401).Produces(429); 14 | return groups; 15 | } 16 | 17 | internal static async Task GetAllTodoItems(IDbContextFactory dbContextFactory, ClaimsPrincipal user, [FromQuery(Name = "page")] int? page = 1, [FromQuery(Name = "pageSize")] int? pageSize = 10) 18 | { 19 | using var dbContext = dbContextFactory.CreateDbContext(); 20 | pageSize ??= 10; 21 | page ??= 1; 22 | 23 | var skipAmount = pageSize * (page - 1); 24 | var queryable = dbContext.TodoItems.Where(t => t.User.Username == user.FindFirst(ClaimTypes.NameIdentifier)!.Value).AsQueryable(); 25 | var results = await queryable 26 | .Skip(skipAmount ?? 1) 27 | .Take(pageSize ?? 10).Select(t => new TodoItemOutput(t.Title, t.IsCompleted, t.CreatedOn)).ToListAsync(); 28 | var totalNumberOfRecords = await queryable.CountAsync(); 29 | var mod = totalNumberOfRecords % pageSize; 30 | var totalPageCount = (totalNumberOfRecords / pageSize) + (mod == 0 ? 0 : 1); 31 | 32 | return TypedResults.Ok(new PagedResults() 33 | { 34 | PageNumber = page.Value, 35 | PageSize = pageSize!.Value, 36 | Results = results, 37 | TotalNumberOfPages = totalPageCount!.Value, 38 | TotalNumberOfRecords = totalNumberOfRecords 39 | }); 40 | } 41 | 42 | internal static async Task GetTodoItemById(IDbContextFactory dbContextFactory, ClaimsPrincipal user, int id) 43 | { 44 | using var dbContext = dbContextFactory.CreateDbContext(); 45 | return await dbContext.TodoItems.FirstOrDefaultAsync(t => t.User.Username == user.FindFirst(ClaimTypes.NameIdentifier)!.Value && t.Id == id) is TodoItem todo ? TypedResults.Ok(new TodoItemOutput(todo.Title, todo.IsCompleted, todo.CreatedOn)) : TypedResults.NotFound(); 46 | } 47 | 48 | internal static async Task CreateTodoItem(IDbContextFactory dbContextFactory, ClaimsPrincipal user, TodoItemInput todoItemInput, IValidator todoItemInputValidator) 49 | { 50 | var validationResult = todoItemInputValidator.Validate(todoItemInput); 51 | if (!validationResult.IsValid) 52 | { 53 | return TypedResults.ValidationProblem(validationResult.ToDictionary()); 54 | } 55 | 56 | using var dbContext = dbContextFactory.CreateDbContext(); 57 | var todoItem = new TodoItem 58 | { 59 | Title = todoItemInput.Title, 60 | IsCompleted = todoItemInput.IsCompleted, 61 | }; 62 | 63 | var currentUser = await dbContext.Users.FirstOrDefaultAsync(t => t.Username == user.FindFirst(ClaimTypes.NameIdentifier)!.Value); 64 | todoItem.User = currentUser!; 65 | todoItem.UserId = currentUser!.Id; 66 | todoItem.CreatedOn = DateTime.UtcNow; 67 | dbContext.TodoItems.Add(todoItem); 68 | await dbContext.SaveChangesAsync(); 69 | return TypedResults.Created($"/todoitems/{todoItem.Id}", new TodoItemOutput(todoItem.Title, todoItem.IsCompleted, todoItem.CreatedOn)); 70 | } 71 | 72 | internal static async Task UpdateTodoItem(IDbContextFactory dbContextFactory, ClaimsPrincipal user, int id, TodoItemInput todoItemInput) 73 | { 74 | using var dbContext = dbContextFactory.CreateDbContext(); 75 | if (await dbContext.TodoItems.FirstOrDefaultAsync(t => t.User.Username == user.FindFirst(ClaimTypes.NameIdentifier)!.Value && t.Id == id) is TodoItem todoItem) 76 | { 77 | todoItem.IsCompleted = todoItemInput.IsCompleted; 78 | await dbContext.SaveChangesAsync(); 79 | return TypedResults.NoContent(); 80 | } 81 | 82 | return TypedResults.NotFound(); 83 | } 84 | 85 | internal static async Task DeleteTodoItem(IDbContextFactory dbContextFactory, ClaimsPrincipal user, int id) 86 | { 87 | using var dbContext = dbContextFactory.CreateDbContext(); 88 | if (await dbContext.TodoItems.FirstOrDefaultAsync(t => t.User.Username == user.FindFirst(ClaimTypes.NameIdentifier)!.Value && t.Id == id) is TodoItem todoItem) 89 | { 90 | dbContext.TodoItems.Remove(todoItem); 91 | await dbContext.SaveChangesAsync(); 92 | return TypedResults.NoContent(); 93 | } 94 | 95 | return TypedResults.NotFound(); 96 | } 97 | } -------------------------------------------------------------------------------- /Source/Usings.cs: -------------------------------------------------------------------------------- 1 | global using FluentValidation; 2 | global using Microsoft.EntityFrameworkCore; 3 | global using Microsoft.Extensions.Diagnostics.HealthChecks; 4 | global using Microsoft.OpenApi.Models; 5 | 6 | global using MinimalApi.Data; 7 | global using MinimalApi.Models; 8 | global using MinimalApi.ViewModels; 9 | 10 | global using System.IdentityModel.Tokens.Jwt; 11 | global using System.Security.Claims; 12 | global using MinimalApi; 13 | global using Asp.Versioning; 14 | 15 | global using System.Diagnostics; 16 | global using System.Net.Http.Headers; 17 | global using System.Threading.RateLimiting; -------------------------------------------------------------------------------- /Source/ViewModels/PagedResults.cs: -------------------------------------------------------------------------------- 1 | namespace MinimalApi.ViewModels 2 | { 3 | public class PagedResults 4 | { 5 | public int PageNumber { get; set; } 6 | public int PageSize { get; set; } 7 | public int TotalNumberOfPages { get; set; } 8 | public int TotalNumberOfRecords { get; set; } 9 | public IEnumerable? Results { get; set; } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Source/ViewModels/TodoItemInput.cs: -------------------------------------------------------------------------------- 1 | namespace MinimalApi.ViewModels; 2 | 3 | public class TodoItemInput 4 | { 5 | public string? Title { get; set; } 6 | public bool IsCompleted { get; set; } 7 | } 8 | -------------------------------------------------------------------------------- /Source/ViewModels/TodoItemInputValidator.cs: -------------------------------------------------------------------------------- 1 | using FluentValidation; 2 | 3 | using Microsoft.EntityFrameworkCore; 4 | 5 | using MinimalApi.Data; 6 | 7 | namespace MinimalApi.ViewModels; 8 | 9 | public class TodoItemInputValidator : AbstractValidator 10 | { 11 | private readonly TodoDbContext _todoDbContext; 12 | public TodoItemInputValidator(IDbContextFactory dbContextFactory) 13 | { 14 | _todoDbContext = dbContextFactory.CreateDbContext(); 15 | 16 | RuleFor(t => t.Title).NotEmpty().MaximumLength(100).MinimumLength(3) 17 | .Must(IsUnique).WithMessage("Title should be unique."); 18 | } 19 | 20 | private bool IsUnique(string title) 21 | { 22 | return !_todoDbContext.TodoItems.Any(t => t.Title == title); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Source/ViewModels/TodoItemOutput.cs: -------------------------------------------------------------------------------- 1 | namespace MinimalApi.ViewModels; 2 | 3 | public class TodoItemOutput 4 | { 5 | public TodoItemOutput(string? title, bool isCompleted, DateTime createdOn) 6 | { 7 | Title = title; 8 | IsCompleted = isCompleted; 9 | CreatedOn = createdOn; 10 | } 11 | 12 | public string? Title { get; set; } 13 | public bool IsCompleted { get; set; } 14 | public DateTime CreatedOn { get; set; } 15 | } -------------------------------------------------------------------------------- /Source/ViewModels/UserInput.cs: -------------------------------------------------------------------------------- 1 | namespace MinimalApi.ViewModels 2 | { 3 | public class UserInput 4 | { 5 | public string? Username { get; set; } 6 | public string? Password { get; set; } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /Source/ViewModels/UserInputValidator.cs: -------------------------------------------------------------------------------- 1 | using FluentValidation; 2 | 3 | namespace MinimalApi.ViewModels 4 | { 5 | public class UserInputValidator : AbstractValidator 6 | { 7 | public UserInputValidator() 8 | { 9 | RuleFor(x => x.Username).NotEmpty(); 10 | RuleFor(x => x.Password).NotEmpty(); 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Source/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.AspNetCore": "Debug", 7 | "Microsoft.Hosting.Lifetime": "Information" 8 | } 9 | }, 10 | "Authentication": { 11 | "Schemes": { 12 | "Bearer": { 13 | "ValidAudiences": [ 14 | "http://localhost:21244", 15 | "https://localhost:44373", 16 | "https://localhost:5001", 17 | "http://localhost:5000" 18 | ], 19 | "ValidIssuer": "dotnet-user-jwts" 20 | } 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /Source/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Debug", 5 | "Microsoft": "Debug", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | }, 9 | "AllowedHosts": "*", 10 | "ConnectionStrings": { 11 | "DefaultConnection": "Server=SOCLAP01;Initial Catalog=TodoDatabase;Persist Security Info=False;User ID=sa;Password=Socxo@123;" 12 | }, 13 | "Issuer" : "https://dotnetthoughts.net/", 14 | "Audience" : "https://dotnetthoughts.net/", 15 | "SigningKey" : "this is my custom Secret key for authentication" 16 | } 17 | -------------------------------------------------------------------------------- /Tests/.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 (console)", 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/MinimalApi.Tests.dll", 14 | "args": [], 15 | "cwd": "${workspaceFolder}", 16 | // For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console 17 | "console": "internalConsole", 18 | "stopAtEntry": false 19 | }, 20 | { 21 | "name": ".NET Core Attach", 22 | "type": "coreclr", 23 | "request": "attach" 24 | } 25 | ] 26 | } -------------------------------------------------------------------------------- /Tests/.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}/MinimalApi.Tests.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}/MinimalApi.Tests.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}/MinimalApi.Tests.csproj" 37 | ], 38 | "problemMatcher": "$msCompile" 39 | } 40 | ] 41 | } -------------------------------------------------------------------------------- /Tests/MinimalApi.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | enable 6 | enable 7 | 8 | false 9 | 10 | 11 | 12 | 13 | runtime; build; native; contentfiles; analyzers; buildtransitive 14 | all 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | runtime; build; native; contentfiles; analyzers; buildtransitive 23 | all 24 | 25 | 26 | runtime; build; native; contentfiles; analyzers; buildtransitive 27 | all 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /Tests/TodoApiIntegrationTests.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc.Testing; 2 | using System.Text; 3 | using System.Net; 4 | using System.Text.Json; 5 | using System.Net.Http.Headers; 6 | using MinimalApi.ViewModels; 7 | 8 | namespace MinimalApi.Tests; 9 | 10 | public class TodoApiIntegrationTests : IClassFixture> 11 | { 12 | private readonly HttpClient _httpClient; 13 | 14 | public TodoApiIntegrationTests(WebApplicationFactory factory) 15 | { 16 | _httpClient = factory.CreateClient(); 17 | } 18 | 19 | [Theory] 20 | [InlineData(true)] 21 | [InlineData(false)] 22 | public async Task DeleteTodoItem(bool getToken = false) 23 | { 24 | if (!getToken) 25 | { 26 | var token = await GetTokenForUser1(); 27 | Assert.NotNull(token); 28 | _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); 29 | } 30 | var response = await _httpClient.DeleteAsync("/todoitems/1"); 31 | var responseStatusCode = response.StatusCode; 32 | 33 | if (!getToken) 34 | { 35 | Assert.Equal(HttpStatusCode.NoContent, responseStatusCode); 36 | } 37 | else 38 | { 39 | Assert.Equal(HttpStatusCode.Unauthorized, responseStatusCode); 40 | } 41 | } 42 | 43 | [Theory] 44 | [InlineData(true)] 45 | [InlineData(false)] 46 | public async Task DeleteTodoItemNonExistingId(bool getToken = false) 47 | { 48 | if (!getToken) 49 | { 50 | var token = await GetTokenForUser1(); 51 | Assert.NotNull(token); 52 | _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); 53 | } 54 | var response = await _httpClient.DeleteAsync("/todoitems/200"); 55 | var responseStatusCode = response.StatusCode; 56 | 57 | if (!getToken) 58 | { 59 | Assert.Equal(HttpStatusCode.NotFound, responseStatusCode); 60 | } 61 | else 62 | { 63 | Assert.Equal(HttpStatusCode.Unauthorized, responseStatusCode); 64 | } 65 | } 66 | 67 | [Theory] 68 | [InlineData(true)] 69 | [InlineData(false)] 70 | public async Task UpdateTodoItem(bool getToken = false) 71 | { 72 | if (!getToken) 73 | { 74 | var token = await GetTokenForUser1(); 75 | Assert.NotNull(token); 76 | _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); 77 | } 78 | var response = await _httpClient.PutAsync("/todoitems/2", 79 | new StringContent(JsonSerializer.Serialize(new TodoItemInput { IsCompleted = true }), 80 | Encoding.UTF8, "application/json")); 81 | var responseStatusCode = response.StatusCode; 82 | 83 | if (!getToken) 84 | { 85 | Assert.Equal(HttpStatusCode.NoContent, responseStatusCode); 86 | } 87 | else 88 | { 89 | Assert.Equal(HttpStatusCode.Unauthorized, responseStatusCode); 90 | } 91 | } 92 | 93 | [Theory] 94 | [InlineData(true)] 95 | [InlineData(false)] 96 | public async Task UpdateTodoItemNonExistingId(bool getToken = false) 97 | { 98 | if (!getToken) 99 | { 100 | var token = await GetTokenForUser1(); 101 | Assert.NotNull(token); 102 | _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); 103 | } 104 | var response = await _httpClient.PutAsync("/todoitems/3000", 105 | new StringContent(JsonSerializer.Serialize(new TodoItemInput { IsCompleted = true }), 106 | Encoding.UTF8, "application/json")); 107 | var responseStatusCode = response.StatusCode; 108 | 109 | if (!getToken) 110 | { 111 | Assert.Equal(HttpStatusCode.NotFound, responseStatusCode); 112 | } 113 | else 114 | { 115 | Assert.Equal(HttpStatusCode.Unauthorized, responseStatusCode); 116 | } 117 | } 118 | 119 | [Theory] 120 | [InlineData(true)] 121 | [InlineData(false)] 122 | public async Task CreateTodoItem(bool getToken = false) 123 | { 124 | if (!getToken) 125 | { 126 | var token = await GetTokenForUser1(); 127 | Assert.NotNull(token); 128 | _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); 129 | } 130 | var response = await _httpClient.PostAsync("/todoitems", 131 | new StringContent(JsonSerializer.Serialize(new TodoItemInput { Title = "Test", IsCompleted = false }), 132 | Encoding.UTF8, "application/json")); 133 | var responseStatusCode = response.StatusCode; 134 | if (!getToken) 135 | { 136 | Assert.Equal(HttpStatusCode.Created, responseStatusCode); 137 | Assert.NotNull(response.Headers.Location); 138 | } 139 | else 140 | { 141 | Assert.Equal(HttpStatusCode.Unauthorized, responseStatusCode); 142 | } 143 | } 144 | 145 | [Theory] 146 | [InlineData(true)] 147 | [InlineData(false)] 148 | public async Task GetTodoItemById(bool getToken = false) 149 | { 150 | if (!getToken) 151 | { 152 | var token = await GetTokenForUser1(); 153 | Assert.NotNull(token); 154 | _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); 155 | } 156 | var response = await _httpClient.GetAsync("/todoitems/5"); 157 | var responseStatusCode = response.StatusCode; 158 | 159 | if (!getToken) 160 | { 161 | Assert.Equal(HttpStatusCode.OK, responseStatusCode); 162 | var todoItems = JsonSerializer.Deserialize(await response.Content.ReadAsStringAsync()); 163 | Assert.NotNull(todoItems); 164 | } 165 | else 166 | { 167 | Assert.Equal(HttpStatusCode.Unauthorized, responseStatusCode); 168 | } 169 | } 170 | 171 | [Theory] 172 | [InlineData(true)] 173 | [InlineData(false)] 174 | public async Task GetTodoItemByIdNonExistingId(bool getToken = false) 175 | { 176 | if (!getToken) 177 | { 178 | var token = await GetTokenForUser1(); 179 | Assert.NotNull(token); 180 | _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); 181 | } 182 | var response = await _httpClient.GetAsync("/todoitems/100"); 183 | var responseStatusCode = response.StatusCode; 184 | 185 | if (!getToken) 186 | { 187 | Assert.Equal(HttpStatusCode.NotFound, responseStatusCode); 188 | } 189 | else 190 | { 191 | Assert.Equal(HttpStatusCode.Unauthorized, responseStatusCode); 192 | } 193 | } 194 | 195 | [Theory] 196 | [InlineData(true)] 197 | [InlineData(false)] 198 | public async Task GetTodoItems(bool getToken = false) 199 | { 200 | if (!getToken) 201 | { 202 | var token = await GetTokenForUser1(); 203 | Assert.NotNull(token); 204 | _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); 205 | } 206 | var response = await _httpClient.GetAsync("/todoitems"); 207 | var responseStatusCode = response.StatusCode; 208 | if (!getToken) 209 | { 210 | Assert.Equal(HttpStatusCode.OK, responseStatusCode); 211 | 212 | var responseContent = await response.Content.ReadAsStringAsync(); 213 | var todoItems = JsonSerializer.Deserialize>(responseContent); 214 | Assert.NotNull(todoItems); 215 | } 216 | else 217 | { 218 | Assert.Equal(HttpStatusCode.Unauthorized, responseStatusCode); 219 | } 220 | } 221 | 222 | [Theory] 223 | [InlineData(true, "1.0")] 224 | [InlineData(false, "1.0")] 225 | [InlineData(true, "2.0")] 226 | [InlineData(false, "2.0")] 227 | public async Task GetTodoItemsWithVersionHeader(bool getToken = false, string version = "1.0") 228 | { 229 | if (!getToken) 230 | { 231 | var token = await GetTokenForUser1(); 232 | Assert.NotNull(token); 233 | _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); 234 | } 235 | _httpClient.DefaultRequestHeaders.Add("api-version", version); 236 | var response = await _httpClient.GetAsync("/todoitems"); 237 | var responseStatusCode = response.StatusCode; 238 | if (!getToken) 239 | { 240 | Assert.Equal(HttpStatusCode.OK, responseStatusCode); 241 | 242 | var responseContent = await response.Content.ReadAsStringAsync(); 243 | var todoItems = JsonSerializer.Deserialize>(responseContent); 244 | Assert.NotNull(todoItems); 245 | } 246 | else 247 | { 248 | Assert.Equal(HttpStatusCode.Unauthorized, responseStatusCode); 249 | } 250 | } 251 | 252 | [Fact(Skip = "Running this test will exhaust the anonymous request limit - which fails the other tests")] 253 | public async Task GetHealthWithoutToken() 254 | { 255 | var response = await _httpClient.GetAsync("/health"); 256 | var responseStatusCode = response.StatusCode; 257 | Assert.Equal(HttpStatusCode.OK, responseStatusCode); 258 | 259 | for (int i = 0; i < 29; i++) 260 | { 261 | response = await _httpClient.GetAsync("/health"); 262 | responseStatusCode = response.StatusCode; 263 | Assert.Equal(HttpStatusCode.OK, responseStatusCode); 264 | } 265 | 266 | response = await _httpClient.GetAsync("/health"); 267 | responseStatusCode = response.StatusCode; 268 | Assert.Equal(HttpStatusCode.TooManyRequests, responseStatusCode); 269 | } 270 | 271 | [Fact] 272 | public async Task GetHealthWithToken() 273 | { 274 | var token = await GetTokenForUser2(); 275 | _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); 276 | var response = await _httpClient.GetAsync("/health"); 277 | var responseStatusCode = response.StatusCode; 278 | Assert.Equal(HttpStatusCode.OK, responseStatusCode); 279 | 280 | for (int i = 0; i < 59; i++) 281 | { 282 | response = await _httpClient.GetAsync("/health"); 283 | responseStatusCode = response.StatusCode; 284 | Assert.Equal(HttpStatusCode.OK, responseStatusCode); 285 | } 286 | 287 | response = await _httpClient.GetAsync("/health"); 288 | responseStatusCode = response.StatusCode; 289 | Assert.Equal(HttpStatusCode.TooManyRequests, responseStatusCode); 290 | } 291 | 292 | private static async Task GetTokenForUser1() 293 | { 294 | var token = Environment.GetEnvironmentVariable("USER1_TOKEN") ?? "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6InVzZXIxIiwic3ViIjoidXNlcjEiLCJqdGkiOiJlNTRlM2JjNyIsIlVzZXJuYW1lIjoidXNlcjEiLCJFbWFpbCI6InVzZXIxQGV4YW1wbGUuY29tIiwiYXVkIjpbImh0dHA6Ly9sb2NhbGhvc3Q6MjEyNDQiLCJodHRwczovL2xvY2FsaG9zdDo0NDM3MyIsImh0dHBzOi8vbG9jYWxob3N0OjUwMDEiLCJodHRwOi8vbG9jYWxob3N0OjUwMDAiXSwibmJmIjoxNzAwMTg2MzE5LCJleHAiOjIwMTU1NDYzMTksImlhdCI6MTcwMDE4NjMyMCwiaXNzIjoiZG90bmV0LXVzZXItand0cyJ9.hf6SeuNrDZXoKj7cFm2FbaswD__M9P2hN6FE4OMSUGg"; 295 | return await Task.Run(() => token); 296 | } 297 | 298 | private static async Task GetTokenForUser2() 299 | { 300 | var token = Environment.GetEnvironmentVariable("USER2_TOKEN") ?? "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6InVzZXIyIiwic3ViIjoidXNlcjIiLCJqdGkiOiI5ZTIzNGY3IiwiVXNlcm5hbWUiOiJ1c2VyMiIsIkVtYWlsIjoidXNlcjJAZXhhbXBsZS5jb20iLCJhdWQiOlsiaHR0cDovL2xvY2FsaG9zdDoyMTI0NCIsImh0dHBzOi8vbG9jYWxob3N0OjQ0MzczIiwiaHR0cHM6Ly9sb2NhbGhvc3Q6NTAwMSIsImh0dHA6Ly9sb2NhbGhvc3Q6NTAwMCJdLCJuYmYiOjE3MDAxODYzNzksImV4cCI6MjAxNTU0NjM3OSwiaWF0IjoxNzAwMTg2MzgwLCJpc3MiOiJkb3RuZXQtdXNlci1qd3RzIn0.mgc7LAtmYcDJXfnmPSXr-kjoAlM7ND89yN5pnffrbpw"; 301 | return await Task.Run(() => token); 302 | } 303 | } -------------------------------------------------------------------------------- /Tests/TodoApiTests.cs: -------------------------------------------------------------------------------- 1 | using System.Security.Claims; 2 | using Microsoft.AspNetCore.Http.HttpResults; 3 | using Microsoft.EntityFrameworkCore; 4 | using MinimalApi.Data; 5 | using MinimalApi.ViewModels; 6 | 7 | namespace MinimalApi.Tests; 8 | 9 | public class TodoApiTests 10 | { 11 | 12 | [Fact] 13 | public async Task GetAllTodoItems_ReturnsOkResultOfIEnumerableTodoItems() 14 | { 15 | var testDbContextFactory = new TestDbContextFactory(); 16 | var user = new ClaimsPrincipal(new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.NameIdentifier, "user1") }, "secret-1")); 17 | 18 | var todoItemsResult = await TodoApi.GetAllTodoItems(testDbContextFactory, user); 19 | 20 | Assert.IsType>>(todoItemsResult); 21 | } 22 | 23 | [Fact] 24 | public async Task GetTodoItemById_ReturnsOkResultOfTodoItem() 25 | { 26 | var testDbContextFactory = new TestDbContextFactory(); 27 | var user = new ClaimsPrincipal(new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.NameIdentifier, "user1") }, "secret-1")); 28 | 29 | var todoItemResult = await TodoApi.GetTodoItemById(testDbContextFactory, user, 1); 30 | 31 | Assert.IsType>(todoItemResult); 32 | } 33 | 34 | [Fact] 35 | public async Task GetTodoItemById_ReturnsNotFound() 36 | { 37 | var testDbContextFactory = new TestDbContextFactory(); 38 | var user = new ClaimsPrincipal(new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.NameIdentifier, "user1") }, "secret-1")); 39 | 40 | var todoItemResult = await TodoApi.GetTodoItemById(testDbContextFactory, user, 100); 41 | 42 | Assert.IsType(todoItemResult); 43 | } 44 | 45 | [Fact] 46 | public async Task CreateTodoItem_ReturnsCreatedStatusWithLocation() 47 | { 48 | var testDbContextFactory = new TestDbContextFactory(); 49 | var user = new ClaimsPrincipal(new ClaimsIdentity( 50 | new Claim[] { new Claim(ClaimTypes.NameIdentifier, "user1") }, "user1")); 51 | var title = "This todo item from Unit test"; 52 | var todoItemInput = new TodoItemInput() { IsCompleted = false, Title = title }; 53 | var todoItemOutputResult = await TodoApi.CreateTodoItem( 54 | testDbContextFactory, user, todoItemInput, new TodoItemInputValidator(testDbContextFactory)); 55 | 56 | Assert.IsType>(todoItemOutputResult); 57 | var createdTodoItemOutput = todoItemOutputResult as Created; 58 | Assert.Equal(201, createdTodoItemOutput!.StatusCode); 59 | var actual = createdTodoItemOutput!.Value!.Title; 60 | Assert.Equal(title, actual); 61 | var actualLocation = createdTodoItemOutput!.Location; 62 | var expectedLocation = $"/todoitems/21"; 63 | Assert.Equal(expectedLocation, actualLocation); 64 | } 65 | 66 | [Fact] 67 | public async Task CreateTodoItem_ReturnsProblem() 68 | { 69 | var testDbContextFactory = new TestDbContextFactory(); 70 | var user = new ClaimsPrincipal(new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.NameIdentifier, "user1") }, "secret-1")); 71 | 72 | var todoItemInput = new TodoItemInput(); 73 | var todoItemOutputResult = await TodoApi.CreateTodoItem(testDbContextFactory, user, todoItemInput, new TodoItemInputValidator(testDbContextFactory)); 74 | 75 | Assert.IsType(todoItemOutputResult); 76 | } 77 | 78 | [Fact] 79 | public async Task UpdateTodoItem_ReturnsNoContent() 80 | { 81 | var testDbContextFactory = new TestDbContextFactory(); 82 | var user = new ClaimsPrincipal(new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.NameIdentifier, "user1") }, "secret-1")); 83 | 84 | var todoItemInput = new TodoItemInput() { IsCompleted = true }; 85 | var result = await TodoApi.UpdateTodoItem(testDbContextFactory, user, 1, todoItemInput); 86 | 87 | Assert.IsType(result); 88 | var updateResult = result as NoContent; 89 | Assert.NotNull(updateResult); 90 | } 91 | 92 | [Fact] 93 | public async Task UpdateTodoItem_ReturnsNotFound() 94 | { 95 | var testDbContextFactory = new TestDbContextFactory(); 96 | var user = new ClaimsPrincipal(new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.NameIdentifier, "user1") }, "secret-1")); 97 | 98 | var todoItemInput = new TodoItemInput() { IsCompleted = true }; 99 | var result = await TodoApi.UpdateTodoItem(testDbContextFactory, user, 205, todoItemInput); 100 | 101 | Assert.IsType(result); 102 | var updateResult = result as NotFound; 103 | Assert.NotNull(updateResult); 104 | } 105 | 106 | [Fact] 107 | public async Task DeleteTodoItem_ReturnsNoContent() 108 | { 109 | var testDbContextFactory = new TestDbContextFactory(); 110 | var user = new ClaimsPrincipal(new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.NameIdentifier, "user1") }, "secret-1")); 111 | 112 | var todoItemInput = new TodoItemInput() { IsCompleted = true }; 113 | var result = await TodoApi.DeleteTodoItem(testDbContextFactory, user, 1); 114 | 115 | Assert.IsType(result); 116 | var deleteResult = result as NoContent; 117 | Assert.NotNull(deleteResult); 118 | } 119 | 120 | [Fact] 121 | public async Task DeleteTodoItem_ReturnsNotFound() 122 | { 123 | var testDbContextFactory = new TestDbContextFactory(); 124 | var user = new ClaimsPrincipal(new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.NameIdentifier, "user1") }, "secret-1")); 125 | 126 | var todoItemInput = new TodoItemInput() { IsCompleted = true }; 127 | var result = await TodoApi.DeleteTodoItem(testDbContextFactory, user, 105); 128 | 129 | Assert.IsType(result); 130 | var deleteResult = result as NotFound; 131 | Assert.NotNull(deleteResult); 132 | } 133 | 134 | } 135 | 136 | public class TestDbContextFactory : IDbContextFactory 137 | { 138 | private DbContextOptions _options; 139 | 140 | public TestDbContextFactory(string databaseName = "InMemoryTest") 141 | { 142 | _options = new DbContextOptionsBuilder() 143 | .UseInMemoryDatabase(databaseName) 144 | .Options; 145 | } 146 | 147 | public TodoDbContext CreateDbContext() 148 | { 149 | var todoDbContext = new TodoDbContext(_options); 150 | todoDbContext.Database.EnsureCreated(); 151 | return todoDbContext; 152 | } 153 | } -------------------------------------------------------------------------------- /Tests/Usings.cs: -------------------------------------------------------------------------------- 1 | global using Xunit; -------------------------------------------------------------------------------- /nuget.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | --------------------------------------------------------------------------------