├── .github └── workflows │ └── aci.yml ├── .gitignore ├── LICENSE ├── README.md ├── TodoList.sln ├── docker-compose.yml └── src ├── TodoList.Api ├── .dockerignore ├── Controllers │ ├── AuthenticationController.cs │ ├── TodoItemController.cs │ ├── TodoItemV2Controller.cs │ ├── TodoListController.cs │ └── WeatherForecastController.cs ├── Dockerfile ├── Dockerfile.prod ├── Extensions │ ├── ApiServiceExtensions.cs │ ├── ExceptionMiddlewareExtensions.cs │ └── RateLimitingServiceExtensions.cs ├── Filters │ └── LogFilterAttribute.cs ├── Middlewares │ └── GlobalExceptionMiddleware.cs ├── Models │ ├── ApiResponse.cs │ └── ErrorResponse.cs ├── Program.cs ├── Properties │ └── launchSettings.json ├── Resources │ ├── Controllers.TodoListController.en-us.Designer.cs │ ├── Controllers.TodoListController.en-us.resx │ ├── Controllers.TodoListController.zh.Designer.cs │ └── Controllers.TodoListController.zh.resx ├── Services │ └── CurrentUserService.cs ├── TodoList.Api.csproj ├── TodoList.Api.xml ├── WeatherForecast.cs ├── appsettings.Development.json ├── appsettings.Production.json ├── appsettings.json ├── aspnetapp.pfx └── tempkey.jwk ├── TodoList.Application ├── Common │ ├── ApplicationHealthCheck.cs │ ├── Behaviors │ │ ├── LoggingBehavior.cs │ │ └── ValidationBehavior.cs │ ├── Configurations │ │ └── JwtConfiguration.cs │ ├── DataShaper.cs │ ├── Exceptions │ │ ├── NotFoundException.cs │ │ └── ValidationException.cs │ ├── Extensions │ │ └── DataShaperExtensions.cs │ ├── Interfaces │ │ ├── IApplicationDbContext.cs │ │ ├── ICurrentUserService.cs │ │ ├── IDataShaper.cs │ │ ├── IDomainEventService.cs │ │ ├── IIdentityService.cs │ │ ├── IRepository.cs │ │ └── ISpecification.cs │ ├── Mappings │ │ ├── IMapFrom.cs │ │ ├── MappingExtensions.cs │ │ └── MappingProfile.cs │ ├── Models │ │ ├── ApplicationToken.cs │ │ ├── DomainEventNotification.cs │ │ ├── Link.cs │ │ ├── LinkCollectionWrapper.cs │ │ ├── LinkResourceBase.cs │ │ ├── PaginatedList.cs │ │ ├── ShapedEntity.cs │ │ └── UserForAuthentication.cs │ ├── SpecificationBase.cs │ └── SpecificationEvaluator.cs ├── DependencyInjection.cs ├── TodoItems │ ├── Commands │ │ ├── CreateTodoItem │ │ │ ├── CreateTodoItemCommand.cs │ │ │ └── CreateTodoItemValidator.cs │ │ ├── PatchTodoItem │ │ │ ├── PatchTodoItemCommand.cs │ │ │ ├── TestPatchTodo.cs │ │ │ └── TodoItemPatchDto.cs │ │ └── UpdateTodoItem │ │ │ └── UpdateTodoItemCommand.cs │ ├── EventHandlers │ │ └── TodoItemCompleteEventHandler.cs │ ├── Queries │ │ └── GetTodoItems │ │ │ ├── GetTodoItemValidator.cs │ │ │ ├── GetTodoItemsWithConditionQuery.cs │ │ │ ├── GetTodoItemsWithPaginationQuery.cs │ │ │ └── TodoItemDto.cs │ └── Specs │ │ └── TodoItemSpec.cs ├── TodoList.Application.csproj └── TodoLists │ ├── Commands │ ├── CreateTodoList │ │ └── CreateTodoListCommand.cs │ └── DeleteTodoList │ │ └── DeleteTodoListCommand.cs │ ├── Queries │ ├── GetSingleTodo │ │ ├── GetSingleTodoQuery.cs │ │ └── TodoListDto.cs │ └── GetTodos │ │ ├── GetTodosQuery.cs │ │ └── TodoListBriefDto.cs │ └── Specs │ └── TodoListSpec.cs ├── TodoList.Domain ├── Base │ ├── AuditableEntity.cs │ ├── DomainEvent.cs │ ├── Interfaces │ │ ├── IAggregateRoot.cs │ │ ├── IEntity.cs │ │ └── IHasDomainEvent.cs │ └── ValueObject.cs ├── Entities │ ├── TodoItem.cs │ └── TodoList.cs ├── Enums │ └── PriorityLevel.cs ├── Events │ ├── TodoItemCompletedEvent.cs │ └── TodoItemCreatedEvent.cs ├── Exceptions │ └── UnsupportedColourException.cs ├── TodoList.Domain.csproj └── ValueObjects │ └── Colour.cs └── TodoList.Infrastructure ├── ApplicationStartupExtensions.cs ├── DependencyInjection.cs ├── Identity ├── ApplicationUser.cs └── IdentityService.cs ├── Log └── ConfigureLogProvider.cs ├── Migrations ├── 20211220092915_SetupDb.Designer.cs ├── 20211220092915_SetupDb.cs ├── 20211222060615_AddEntities.Designer.cs ├── 20211222060615_AddEntities.cs ├── 20220108060343_AddIdentities.Designer.cs ├── 20220108060343_AddIdentities.cs ├── 20220108073037_AddIdentitiesWithCredentials.Designer.cs ├── 20220108073037_AddIdentitiesWithCredentials.cs ├── 20220108141927_UseIdentityIsteadofServer.Designer.cs ├── 20220108141927_UseIdentityIsteadofServer.cs ├── 20220109065325_AddRefreshToken.Designer.cs ├── 20220109065325_AddRefreshToken.cs └── TodoListDbContextModelSnapshot.cs ├── Persistence ├── Configurations │ ├── TodoItemConfiguration.cs │ └── TodoListConfiguration.cs ├── Repositories │ └── RepositoryBase.cs ├── TodoListDbContext.cs └── TodoListDbContextSeed.cs ├── Services └── DomainEventService.cs └── TodoList.Infrastructure.csproj /.github/workflows/aci.yml: -------------------------------------------------------------------------------- 1 | on: [push] 2 | name: Linux_Container_Workflow 3 | 4 | jobs: 5 | build-and-deploy: 6 | runs-on: ubuntu-latest 7 | steps: 8 | # checkout the repo 9 | - name: 'Checkout GitHub Action' 10 | uses: actions/checkout@main 11 | 12 | - name: 'Login via Azure CLI' 13 | uses: azure/login@v1 14 | with: 15 | creds: ${{ secrets.AZURE_CREDENTIALS }} 16 | 17 | - name: 'Build and push image' 18 | uses: azure/docker-login@v1 19 | with: 20 | login-server: ${{ secrets.REGISTRY_LOGIN_SERVER }} 21 | username: ${{ secrets.REGISTRY_USERNAME }} 22 | password: ${{ secrets.REGISTRY_PASSWORD }} 23 | - run: | 24 | docker build -f src/TodoList.Api/Dockerfile.prod . -t ${{ secrets.REGISTRY_LOGIN_SERVER }}/todolist:${{ github.sha }} 25 | docker push ${{ secrets.REGISTRY_LOGIN_SERVER }}/todolist:${{ github.sha }} 26 | - name: 'Deploy to Azure Container Instances' 27 | uses: 'azure/aci-deploy@v1' 28 | with: 29 | resource-group: ${{ secrets.RESOURCE_GROUP }} 30 | dns-name-label: ${{ secrets.RESOURCE_GROUP }}${{ github.run_number }} 31 | image: ${{ secrets.REGISTRY_LOGIN_SERVER }}/todolist:${{ github.sha }} 32 | registry-login-server: ${{ secrets.REGISTRY_LOGIN_SERVER }} 33 | registry-username: ${{ secrets.REGISTRY_USERNAME }} 34 | registry-password: ${{ secrets.REGISTRY_PASSWORD }} 35 | name: aci-todolist 36 | location: 'east asia' 37 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | gnore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Build results 17 | [Dd]ebug/ 18 | [Dd]ebugPublic/ 19 | [Rr]elease/ 20 | [Rr]eleases/ 21 | x64/ 22 | x86/ 23 | [Aa][Rr][Mm]/ 24 | [Aa][Rr][Mm]64/ 25 | bld/ 26 | [Bb]in/ 27 | [Oo]bj/ 28 | 29 | # Visual Studio 2015/2017 cache/options directory 30 | .vs/ 31 | # Uncomment if you have tasks that create the project's static files in wwwroot 32 | **/wwwroot/dist 33 | 34 | # node/npm/yarn related 35 | **/logs 36 | **/*.log 37 | **/npm-debug.log* 38 | **/yarn-debug.log* 39 | **/yarn-error.log* 40 | **/.npm 41 | **/.eslintcache 42 | **/.yarn-integrity 43 | 44 | # Docker environment settings 45 | .env 46 | 47 | 48 | #VSCode 49 | .vscode/* 50 | !.vscode/settings.json 51 | !.vscode/tasks.json 52 | !.vscode/launch.json 53 | !.vscode/extensions.json 54 | 55 | # Visual Studio 2017 auto generated files 56 | Generated\ Files/ 57 | 58 | # MSTest test Results 59 | [Tt]est[Rr]esult*/ 60 | [Bb]uild[Ll]og.* 61 | 62 | # NUNIT 63 | *.VisualState.xml 64 | TestResult.xml 65 | 66 | # Build Results of an ATL Project 67 | [Dd]ebugPS/ 68 | [Rr]eleasePS/ 69 | dlldata.c 70 | 71 | # Benchmark Results 72 | BenchmarkDotNet.Artifacts/ 73 | 74 | # .NET Core 75 | project.lock.json 76 | project.fragment.lock.json 77 | artifacts/ 78 | 79 | # StyleCop 80 | StyleCopReport.xml 81 | 82 | # Files built by Visual Studio 83 | *_i.c 84 | *_p.c 85 | *_h.h 86 | *.ilk 87 | *.meta 88 | *.obj 89 | *.iobj 90 | *.pch 91 | *.pdb 92 | *.ipdb 93 | *.pgc 94 | *.pgd 95 | *.rsp 96 | *.sbr 97 | *.tlb 98 | *.tli 99 | *.tlh 100 | *.tmp 101 | *.tmp_proj 102 | *_wpftmp.csproj 103 | *.log 104 | *.vspscc 105 | *.vssscc 106 | .builds 107 | *.pidb 108 | *.svclog 109 | *.scc 110 | 111 | # Chutzpah Test files 112 | _Chutzpah* 113 | 114 | # Visual C++ cache files 115 | ipch/ 116 | *.aps 117 | *.ncb 118 | *.opendb 119 | *.opensdf 120 | *.sdf 121 | *.cachefile 122 | *.VC.db 123 | *.VC.VC.opendb 124 | 125 | # Visual Studio profiler 126 | *.psess 127 | *.vsp 128 | *.vspx 129 | *.sap 130 | 131 | # Visual Studio Trace Files 132 | *.e2e 133 | 134 | # TFS 2012 Local Workspace 135 | $tf/ 136 | 137 | # Guidance Automation Toolkit 138 | *.gpState 139 | 140 | # ReSharper is a .NET coding add-in 141 | _ReSharper*/ 142 | *.[Rr]e[Ss]harper 143 | *.DotSettings.user 144 | 145 | # JustCode is a .NET coding add-in 146 | .JustCode 147 | 148 | # TeamCity is a build add-in 149 | _TeamCity* 150 | 151 | # DotCover is a Code Coverage Tool 152 | *.dotCover 153 | 154 | # AxoCover is a Code Coverage Tool 155 | .axoCover/* 156 | !.axoCover/settings.json 157 | 158 | # Visual Studio code coverage results 159 | *.coverage 160 | *.coveragexml 161 | 162 | # NCrunch 163 | _NCrunch_* 164 | .*crunch*.local.xml 165 | nCrunchTemp_* 166 | 167 | # MightyMoose 168 | *.mm.* 169 | AutoTest.Net/ 170 | 171 | # Web workbench (sass) 172 | .sass-cache/ 173 | 174 | # Installshield output folder 175 | [Ee]xpress/ 176 | 177 | # DocProject is a documentation generator add-in 178 | DocProject/buildhelp/ 179 | DocProject/Help/*.HxT 180 | DocProject/Help/*.HxC 181 | DocProject/Help/*.hhc 182 | DocProject/Help/*.hhk 183 | DocProject/Help/*.hhp 184 | DocProject/Help/Html2 185 | DocProject/Help/html 186 | 187 | # Click-Once directory 188 | publish/ 189 | 190 | # Publish Web Output 191 | *.[Pp]ublish.xml 192 | *.azurePubxml 193 | # Note: Comment the next line if you want to checkin your web deploy settings, 194 | # but database connection strings (with potential passwords) will be unencrypted 195 | *.pubxml 196 | *.publishproj 197 | 198 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 199 | # checkin your Azure Web App publish settings, but sensitive information contained 200 | # in these scripts will be unencrypted 201 | PublishScripts/ 202 | 203 | # NuGet Packages 204 | *.nupkg 205 | # The packages folder can be ignored because of Package Restore 206 | **/[Pp]ackages/* 207 | # except build/, which is used as an MSBuild target. 208 | !**/[Pp]ackages/build/ 209 | # Uncomment if necessary however generally it will be regenerated when needed 210 | #!**/[Pp]ackages/repositories.config 211 | # NuGet v3's project.json files produces more ignorable files 212 | *.nuget.props 213 | *.nuget.targets 214 | 215 | # Microsoft Azure Build Output 216 | csx/ 217 | *.build.csdef 218 | 219 | # Microsoft Azure Emulator 220 | ecf/ 221 | rcf/ 222 | 223 | # Windows Store app package directories and files 224 | AppPackages/ 225 | BundleArtifacts/ 226 | Package.StoreAssociation.xml 227 | _pkginfo.txt 228 | *.appx 229 | 230 | # Visual Studio cache files 231 | # files ending in .cache can be ignored 232 | *.[Cc]ache 233 | # but keep track of directories ending in .cache 234 | !?*.[Cc]ache/ 235 | 236 | # Others 237 | ClientBin/ 238 | ~$* 239 | *~ 240 | *.dbmdl 241 | *.dbproj.schemaview 242 | *.jfm 243 | *.pfx 244 | *.publishsettings 245 | orleans.codegen.cs 246 | 247 | # Including strong name files can present a security risk 248 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 249 | #*.snk 250 | 251 | # Since there are multiple workflows, uncomment next line to ignore bower_components 252 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 253 | #bower_components/ 254 | # ASP.NET Core default setup: bower directory is configured as wwwroot/lib/ and bower restore is true 255 | **/wwwroot/lib/ 256 | 257 | # RIA/Silverlight projects 258 | Generated_Code/ 259 | 260 | # Backup & report files from converting an old project file 261 | # to a newer Visual Studio version. Backup files are not needed, 262 | # because we have git ;-) 263 | _UpgradeReport_Files/ 264 | Backup*/ 265 | UpgradeLog*.XML 266 | UpgradeLog*.htm 267 | ServiceFabricBackup/ 268 | *.rptproj.bak 269 | 270 | # SQL Server files 271 | *.mdf 272 | *.ldf 273 | *.ndf 274 | 275 | # Business Intelligence projects 276 | *.rdl.data 277 | *.bim.layout 278 | *.bim_*.settings 279 | *.rptproj.rsuser 280 | 281 | # Microsoft Fakes 282 | FakesAssemblies/ 283 | 284 | # GhostDoc plugin setting file 285 | *.GhostDoc.xml 286 | 287 | # Node.js Tools for Visual Studio 288 | .ntvs_analysis.dat 289 | node_modules/ 290 | 291 | # Visual Studio 6 build log 292 | *.plg 293 | 294 | # Visual Studio 6 workspace options file 295 | *.opt 296 | 297 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 298 | *.vbw 299 | 300 | # Visual Studio LightSwitch build output 301 | **/*.HTMLClient/GeneratedArtifacts 302 | **/*.DesktopClient/GeneratedArtifacts 303 | **/*.DesktopClient/ModelManifest.xml 304 | **/*.Server/GeneratedArtifacts 305 | **/*.Server/ModelManifest.xml 306 | _Pvt_Extensions 307 | 308 | # Paket dependency manager 309 | .paket/paket.exe 310 | paket-files/ 311 | 312 | # FAKE - F# Make 313 | .fake/ 314 | 315 | # JetBrains Rider 316 | .idea/ 317 | *.sln.iml 318 | 319 | # CodeRush personal settings 320 | .cr/personal 321 | 322 | # Python Tools for Visual Studio (PTVS) 323 | __pycache__/ 324 | *.pyc 325 | 326 | # Cake - Uncomment if you are using it 327 | # tools/** 328 | # !tools/packages.config 329 | 330 | # Tabs Studio 331 | *.tss 332 | 333 | # Telerik's JustMock configuration file 334 | *.jmconfig 335 | 336 | # BizTalk build output 337 | *.btp.cs 338 | *.btm.cs 339 | *.odx.cs 340 | *.xsd.cs 341 | 342 | # OpenCover UI analysis results 343 | OpenCover/ 344 | 345 | # Azure Stream Analytics local run output 346 | ASALocalRun/ 347 | 348 | # MSBuild Binary and Structured Log 349 | *.binlog 350 | 351 | # NVidia Nsight GPU debugger configuration file 352 | *.nvuser 353 | 354 | # MFractors (Xamarin productivity tool) working folder 355 | .mfractor/ 356 | 357 | # Local History for Visual Studio 358 | .localhistory/ 359 | 360 | # BeatPulse healthcheck temp database 361 | healthchecksdb 362 | 363 | 364 | # dotenv environment variables file 365 | .env 366 | 367 | # next.js build output 368 | .next 369 | .DS_Store 370 | .vscode/ 371 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Asinta 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # TodoList 2 | 3 | 博客园系列文章:[使用.NET 6开发TodoList应用文章索引](https://www.cnblogs.com/code4nothing/p/build-todolist-index.html) 4 | -------------------------------------------------------------------------------- /TodoList.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("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{8AE659E2-5CDB-45A2-A6CE-76D0F92F65A1}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TodoList.Api", "src\TodoList.Api\TodoList.Api.csproj", "{9D11A89D-4E82-4DDA-A513-6BBB6286FF19}" 9 | EndProject 10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TodoList.Application", "src\TodoList.Application\TodoList.Application.csproj", "{BD872F50-5356-410E-A9C8-D6EAF9E4BA9E}" 11 | EndProject 12 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TodoList.Domain", "src\TodoList.Domain\TodoList.Domain.csproj", "{17FC7E69-7DC0-41B3-8FDF-FD70F12D8052}" 13 | EndProject 14 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TodoList.Infrastructure", "src\TodoList.Infrastructure\TodoList.Infrastructure.csproj", "{947BF876-10CB-4A12-9E78-021BAF50D776}" 15 | EndProject 16 | Global 17 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 18 | Debug|Any CPU = Debug|Any CPU 19 | Release|Any CPU = Release|Any CPU 20 | EndGlobalSection 21 | GlobalSection(SolutionProperties) = preSolution 22 | HideSolutionNode = FALSE 23 | EndGlobalSection 24 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 25 | {9D11A89D-4E82-4DDA-A513-6BBB6286FF19}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 26 | {9D11A89D-4E82-4DDA-A513-6BBB6286FF19}.Debug|Any CPU.Build.0 = Debug|Any CPU 27 | {9D11A89D-4E82-4DDA-A513-6BBB6286FF19}.Release|Any CPU.ActiveCfg = Release|Any CPU 28 | {9D11A89D-4E82-4DDA-A513-6BBB6286FF19}.Release|Any CPU.Build.0 = Release|Any CPU 29 | {BD872F50-5356-410E-A9C8-D6EAF9E4BA9E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 30 | {BD872F50-5356-410E-A9C8-D6EAF9E4BA9E}.Debug|Any CPU.Build.0 = Debug|Any CPU 31 | {BD872F50-5356-410E-A9C8-D6EAF9E4BA9E}.Release|Any CPU.ActiveCfg = Release|Any CPU 32 | {BD872F50-5356-410E-A9C8-D6EAF9E4BA9E}.Release|Any CPU.Build.0 = Release|Any CPU 33 | {17FC7E69-7DC0-41B3-8FDF-FD70F12D8052}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 34 | {17FC7E69-7DC0-41B3-8FDF-FD70F12D8052}.Debug|Any CPU.Build.0 = Debug|Any CPU 35 | {17FC7E69-7DC0-41B3-8FDF-FD70F12D8052}.Release|Any CPU.ActiveCfg = Release|Any CPU 36 | {17FC7E69-7DC0-41B3-8FDF-FD70F12D8052}.Release|Any CPU.Build.0 = Release|Any CPU 37 | {947BF876-10CB-4A12-9E78-021BAF50D776}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 38 | {947BF876-10CB-4A12-9E78-021BAF50D776}.Debug|Any CPU.Build.0 = Debug|Any CPU 39 | {947BF876-10CB-4A12-9E78-021BAF50D776}.Release|Any CPU.ActiveCfg = Release|Any CPU 40 | {947BF876-10CB-4A12-9E78-021BAF50D776}.Release|Any CPU.Build.0 = Release|Any CPU 41 | EndGlobalSection 42 | GlobalSection(NestedProjects) = preSolution 43 | {9D11A89D-4E82-4DDA-A513-6BBB6286FF19} = {8AE659E2-5CDB-45A2-A6CE-76D0F92F65A1} 44 | {BD872F50-5356-410E-A9C8-D6EAF9E4BA9E} = {8AE659E2-5CDB-45A2-A6CE-76D0F92F65A1} 45 | {17FC7E69-7DC0-41B3-8FDF-FD70F12D8052} = {8AE659E2-5CDB-45A2-A6CE-76D0F92F65A1} 46 | {947BF876-10CB-4A12-9E78-021BAF50D776} = {8AE659E2-5CDB-45A2-A6CE-76D0F92F65A1} 47 | EndGlobalSection 48 | EndGlobal 49 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3.4' 2 | 3 | services: 4 | todo-list: 5 | image: todo-list 6 | # 配置端口转发 7 | ports: 8 | - "80:80" 9 | - "5001:443" 10 | # 配置容器环境变量 11 | environment: 12 | - ASPNETCORE_ENVIRONMENT=Development 13 | - ASPNETCORE_URLS=https://+;http://+ 14 | - ASPNETCORE_HTTPS_PORT=5001 15 | - ASPNETCORE_Kestrel__Certificates__Default__Password=Test@Password 16 | - ASPNETCORE_Kestrel__Certificates__Default__Path=/https/aspnetapp.pfx 17 | # 挂载证书路径 18 | volumes: 19 | - ~/.aspnet/https:/https:ro 20 | # 需要先启动数据库容器 21 | depends_on: 22 | - mssql 23 | # todo-list通过public网络响应请求,通过private网络连接数据库容器 24 | networks: 25 | - private 26 | - public 27 | 28 | mssql: 29 | image: mcr.microsoft.com/mssql/server:2019-latest 30 | # 配置端口转发,这是为从主机直接访问数据库需要的,如果没有从主机直接访问数据库的需求,只需要声明容器端口1433不做转发即可 31 | ports: 32 | - "1433:1433" 33 | environment: 34 | - SA_PASSWORD=StrongPwd123 35 | - ACCEPT_EULA=Y 36 | # 挂载数据目录实现持久化 37 | volumes: 38 | - mssqldata:/var/opt/mssql 39 | networks: 40 | - private 41 | - public 42 | 43 | # 因为mssqldata路径之前已经创建了,所以需要在这里声明使用已有的 44 | volumes: 45 | mssqldata: 46 | 47 | networks: 48 | private: 49 | public: -------------------------------------------------------------------------------- /src/TodoList.Api/.dockerignore: -------------------------------------------------------------------------------- 1 | **/.dockerignore 2 | **/.env 3 | **/.git 4 | **/.gitignore 5 | **/.project 6 | **/.settings 7 | **/.toolstarget 8 | **/.vs 9 | **/.vscode 10 | **/.idea 11 | **/*.*proj.user 12 | **/*.dbmdl 13 | **/*.jfm 14 | **/azds.yaml 15 | **/bin 16 | **/charts 17 | **/docker-compose* 18 | **/Dockerfile* 19 | **/node_modules 20 | **/npm-debug.log 21 | **/obj 22 | **/secrets.dev.yaml 23 | **/values.dev.yaml 24 | LICENSE 25 | README.md -------------------------------------------------------------------------------- /src/TodoList.Api/Controllers/AuthenticationController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | using TodoList.Application.Common.Interfaces; 3 | using TodoList.Application.Common.Models; 4 | 5 | namespace TodoList.Api.Controllers; 6 | 7 | [ApiController] 8 | public class AuthenticationController : ControllerBase 9 | { 10 | private readonly IIdentityService _identityService; 11 | private readonly ILogger _logger; 12 | 13 | public AuthenticationController(IIdentityService identityService, ILogger logger) 14 | { 15 | _identityService = identityService; 16 | _logger = logger; 17 | } 18 | 19 | [HttpPost("login")] 20 | public async Task Authenticate([FromBody] UserForAuthentication userForAuthentication) 21 | { 22 | if (!await _identityService.ValidateUserAsync(userForAuthentication)) 23 | { 24 | return Unauthorized(); 25 | } 26 | 27 | var token = await _identityService.CreateTokenAsync(true); 28 | return Ok(token); 29 | } 30 | 31 | [HttpPost("refresh")] 32 | public async Task Refresh([FromBody] ApplicationToken token) 33 | { 34 | var tokenToReturn = await _identityService.RefreshTokenAsync(token); 35 | 36 | return Ok(tokenToReturn); 37 | } 38 | } -------------------------------------------------------------------------------- /src/TodoList.Api/Controllers/TodoItemController.cs: -------------------------------------------------------------------------------- 1 | using System.Dynamic; 2 | using MediatR; 3 | using Microsoft.AspNetCore.JsonPatch; 4 | using Microsoft.AspNetCore.Mvc; 5 | using TodoList.Api.Models; 6 | using TodoList.Application.Common.Models; 7 | using TodoList.Application.TodoItems.Commands.CreateTodoItem; 8 | using TodoList.Application.TodoItems.Commands.PatchTodoItem; 9 | using TodoList.Application.TodoItems.Commands.UpdateTodoItem; 10 | using TodoList.Application.TodoItems.Queries.GetTodoItems; 11 | using TodoList.Domain.Entities; 12 | 13 | namespace TodoList.Api.Controllers; 14 | 15 | 16 | [Route("/todo-item")] 17 | [ApiExplorerSettings(GroupName = "1.0")] 18 | [ApiController] 19 | public class TodoItemController : ControllerBase 20 | { 21 | private readonly IMediator _mediator; 22 | 23 | // 注入MediatR 24 | public TodoItemController(IMediator mediator) 25 | => _mediator = mediator; 26 | 27 | [HttpPost] 28 | public async Task> Create([FromBody] CreateTodoItemCommand command) 29 | { 30 | return ApiResponse.Success(await _mediator.Send(command)); 31 | } 32 | 33 | [HttpPut("{id:Guid}")] 34 | public async Task> Update(Guid id, [FromBody] UpdateTodoItemCommand command) 35 | { 36 | if (id != command.Id) 37 | { 38 | return ApiResponse.Fail("Query id not match witch body"); 39 | } 40 | 41 | return ApiResponse.Success(await _mediator.Send(command)); 42 | } 43 | 44 | [HttpPatch("{id:guid}")] 45 | public async Task> Patch(Guid id, [FromBody] JsonPatchDocument command) 46 | { 47 | if (command is null) 48 | { 49 | return ApiResponse.Fail("patch document should not be null"); 50 | } 51 | 52 | // if (id != command.Id) 53 | // { 54 | // return ApiResponse.Fail("Query id not match witch body"); 55 | // } 56 | return ApiResponse.Fail("BINGO"); 57 | 58 | 59 | // return ApiResponse.Success(await _mediator.Send(command)); 60 | } 61 | 62 | // 对于查询来说,一般参数是来自查询字符串的,所以这里用[FromQuery] 63 | [HttpGet] 64 | [HttpHead] 65 | public async Task>> GetTodoItemsWithCondition([FromQuery] GetTodoItemsWithConditionQuery query) 66 | { 67 | return ApiResponse>.Success(await _mediator.Send(query)); 68 | } 69 | 70 | [HttpOptions] 71 | public Task> GetTodoItemsOptions() 72 | { 73 | Response.Headers.Add("Allow", "GET, OPTIONS, POST, PUT"); 74 | 75 | return Task.FromResult(ApiResponse.Success("")); 76 | } 77 | } -------------------------------------------------------------------------------- /src/TodoList.Api/Controllers/TodoItemV2Controller.cs: -------------------------------------------------------------------------------- 1 | using System.Dynamic; 2 | using MediatR; 3 | using Microsoft.AspNetCore.JsonPatch; 4 | using Microsoft.AspNetCore.Mvc; 5 | using TodoList.Api.Models; 6 | using TodoList.Application.Common.Models; 7 | using TodoList.Application.TodoItems.Commands.CreateTodoItem; 8 | using TodoList.Application.TodoItems.Commands.PatchTodoItem; 9 | using TodoList.Application.TodoItems.Commands.UpdateTodoItem; 10 | using TodoList.Application.TodoItems.Queries.GetTodoItems; 11 | using TodoList.Domain.Entities; 12 | 13 | namespace TodoList.Api.Controllers; 14 | 15 | [Route("/todo-item")] 16 | [ApiExplorerSettings(GroupName = "2.0")] 17 | [ApiController] 18 | public class TodoItemV2Controller : ControllerBase 19 | { 20 | private readonly IMediator _mediator; 21 | 22 | // 注入MediatR 23 | public TodoItemV2Controller(IMediator mediator) => _mediator = mediator; 24 | 25 | [HttpPost] 26 | public async Task> Create([FromBody] CreateTodoItemCommand command) 27 | { 28 | return ApiResponse.Success(await _mediator.Send(command)); 29 | } 30 | 31 | [HttpPut("{id:Guid}")] 32 | public async Task> Update(Guid id, [FromBody] UpdateTodoItemCommand command) 33 | { 34 | if (id != command.Id) 35 | { 36 | return ApiResponse.Fail("Query id not match witch body"); 37 | } 38 | 39 | return ApiResponse.Success(await _mediator.Send(command)); 40 | } 41 | 42 | [HttpPatch("{id:guid}")] 43 | public async Task> Patch(Guid id, [FromBody] JsonPatchDocument command) 44 | { 45 | if (command is null) 46 | { 47 | return ApiResponse.Fail("patch document should not be null"); 48 | } 49 | 50 | // if (id != command.Id) 51 | // { 52 | // return ApiResponse.Fail("Query id not match witch body"); 53 | // } 54 | return ApiResponse.Fail("BINGO"); 55 | 56 | 57 | // return ApiResponse.Success(await _mediator.Send(command)); 58 | } 59 | 60 | // 对于查询来说,一般参数是来自查询字符串的,所以这里用[FromQuery] 61 | [HttpGet] 62 | [HttpHead] 63 | public async Task>> GetTodoItemsWithCondition([FromQuery] GetTodoItemsWithConditionQuery query) 64 | { 65 | return ApiResponse>.Success(await _mediator.Send(query)); 66 | } 67 | 68 | [HttpOptions] 69 | public Task> GetTodoItemsOptions() 70 | { 71 | Response.Headers.Add("Allow", "GET, OPTIONS, POST, PUT"); 72 | 73 | return Task.FromResult(ApiResponse.Success("")); 74 | } 75 | } -------------------------------------------------------------------------------- /src/TodoList.Api/Controllers/TodoListController.cs: -------------------------------------------------------------------------------- 1 | using MediatR; 2 | using Microsoft.AspNetCore.Authorization; 3 | using Microsoft.AspNetCore.Mvc; 4 | using Microsoft.Extensions.Localization; 5 | using TodoList.Api.Filters; 6 | using TodoList.Api.Models; 7 | using TodoList.Application.TodoLists.Commands.CreateTodoList; 8 | using TodoList.Application.TodoLists.Commands.DeleteTodoList; 9 | using TodoList.Application.TodoLists.Queries.GetSingleTodo; 10 | using TodoList.Application.TodoLists.Queries.GetTodos; 11 | 12 | namespace TodoList.Api.Controllers; 13 | 14 | [ApiController] 15 | [Authorize] 16 | [Route("/todo-list")] 17 | public class TodoListController : ControllerBase 18 | { 19 | private readonly IMediator _mediator; 20 | private readonly IStringLocalizer _localizer; 21 | 22 | // 注入MediatR 23 | public TodoListController(IMediator mediator, IStringLocalizer localizer) 24 | { 25 | _mediator = mediator; 26 | _localizer = localizer; 27 | } 28 | 29 | [HttpGet("meta")] 30 | public ApiResponse GetTodoListMeta() 31 | { 32 | var response = ApiResponse.Success(_localizer["TodoListMeta"]); 33 | return response; 34 | } 35 | 36 | [HttpGet] 37 | public async Task>> Get() 38 | { 39 | return ApiResponse>.Success(await _mediator.Send(new GetTodosQuery())); 40 | } 41 | 42 | [HttpGet("{id:Guid}", Name = "TodListById")] 43 | public async Task> GetSingleTodoList(Guid id) 44 | { 45 | return ApiResponse.Success(await _mediator.Send(new GetSingleTodoQuery { ListId = id }) ?? 46 | throw new InvalidOperationException()); 47 | } 48 | 49 | /// 50 | /// 创建新的TodoList,只有Administrator角色的用户有此权限 51 | /// 52 | /// 创建TodoList命令 53 | /// 54 | [HttpPost] 55 | [Authorize(Policy = "OnlyAdmin")] 56 | [ServiceFilter(typeof(LogFilterAttribute))] 57 | public async Task> Create([FromBody] CreateTodoListCommand command) 58 | { 59 | return ApiResponse.Success(await _mediator.Send(command)); 60 | } 61 | 62 | [HttpDelete("{id:guid}")] 63 | public async Task> Delete(Guid id) 64 | { 65 | return ApiResponse.Success(await _mediator.Send(new DeleteTodoListCommand { Id = id })); 66 | } 67 | } -------------------------------------------------------------------------------- /src/TodoList.Api/Controllers/WeatherForecastController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | 3 | namespace TodoList.Api.Controllers; 4 | 5 | [ApiController] 6 | [Route("[controller]")] 7 | public class WeatherForecastController : ControllerBase 8 | { 9 | private static readonly string[] Summaries = new[] 10 | { 11 | "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" 12 | }; 13 | 14 | private readonly ILogger _logger; 15 | 16 | // 为了验证,临时在这注入IRepository对象,验证完后撤销修改 17 | public WeatherForecastController(ILogger logger) 18 | { 19 | _logger = logger; 20 | } 21 | 22 | [HttpGet(Name = "GetWeatherForecast")] 23 | public IEnumerable Get() 24 | { 25 | // 记录日志 26 | _logger.LogInformation($"maybe this log is provided by Serilog..."); 27 | 28 | return Enumerable.Range(1, 5).Select(index => new WeatherForecast 29 | { 30 | Date = DateTime.Now.AddDays(index), 31 | TemperatureC = Random.Shared.Next(-20, 55), 32 | Summary = Summaries[Random.Shared.Next(Summaries.Length)] 33 | }) 34 | .ToArray(); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/TodoList.Api/Dockerfile: -------------------------------------------------------------------------------- 1 | ARG NET_IMAGE=6.0-bullseye-slim 2 | FROM mcr.microsoft.com/dotnet/aspnet:${NET_IMAGE} AS base 3 | WORKDIR /app 4 | EXPOSE 80 5 | EXPOSE 443 6 | ENV ASPNETCORE_ENVIRONMENT Development 7 | 8 | FROM mcr.microsoft.com/dotnet/sdk:${NET_IMAGE} AS build 9 | WORKDIR /src 10 | COPY ["src/TodoList.Api/TodoList.Api.csproj", "TodoList.Api/"] 11 | COPY ["src/TodoList.Application/TodoList.Application.csproj", "TodoList.Application/"] 12 | COPY ["src/TodoList.Domain/TodoList.Domain.csproj", "TodoList.Domain/"] 13 | COPY ["src/TodoList.Infrastructure/TodoList.Infrastructure.csproj", "TodoList.Infrastructure/"] 14 | RUN dotnet restore "TodoList.Api/TodoList.Api.csproj" 15 | COPY ./src . 16 | WORKDIR "/src/TodoList.Api" 17 | RUN dotnet build "TodoList.Api.csproj" -c Release -o /app/build 18 | 19 | FROM build AS publish 20 | RUN dotnet publish --no-restore "TodoList.Api.csproj" -c Release -o /app/publish 21 | 22 | FROM base AS final 23 | WORKDIR /app 24 | COPY --from=publish /app/publish . 25 | ENTRYPOINT ["dotnet", "TodoList.Api.dll"] 26 | -------------------------------------------------------------------------------- /src/TodoList.Api/Dockerfile.prod: -------------------------------------------------------------------------------- 1 | ARG NET_IMAGE=6.0-bullseye-slim 2 | FROM mcr.microsoft.com/dotnet/aspnet:${NET_IMAGE} AS base 3 | WORKDIR /app 4 | EXPOSE 80 5 | 6 | ENV ASPNETCORE_ENVIRONMENT=Production 7 | 8 | 9 | FROM mcr.microsoft.com/dotnet/sdk:${NET_IMAGE} AS build 10 | WORKDIR /src 11 | COPY ["src/TodoList.Api/TodoList.Api.csproj", "TodoList.Api/"] 12 | COPY ["src/TodoList.Application/TodoList.Application.csproj", "TodoList.Application/"] 13 | COPY ["src/TodoList.Domain/TodoList.Domain.csproj", "TodoList.Domain/"] 14 | COPY ["src/TodoList.Infrastructure/TodoList.Infrastructure.csproj", "TodoList.Infrastructure/"] 15 | RUN dotnet restore "TodoList.Api/TodoList.Api.csproj" 16 | COPY ./src . 17 | WORKDIR "/src/TodoList.Api" 18 | RUN dotnet build "TodoList.Api.csproj" -c Release -o /app/build 19 | 20 | FROM build AS publish 21 | RUN dotnet publish --no-restore "TodoList.Api.csproj" -c Release -o /app/publish 22 | 23 | FROM base AS final 24 | WORKDIR /app 25 | COPY --from=publish /app/publish . 26 | ENTRYPOINT ["dotnet", "TodoList.Api.dll"] 27 | -------------------------------------------------------------------------------- /src/TodoList.Api/Extensions/ApiServiceExtensions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | using Microsoft.AspNetCore.Mvc.Versioning; 3 | using TodoList.Api.Controllers; 4 | 5 | namespace TodoList.Api.Extensions; 6 | 7 | public static class ApiServiceExtensions 8 | { 9 | public static void ConfigureApiVersioning(this IServiceCollection services) 10 | { 11 | services.AddApiVersioning(options => 12 | { 13 | // 向响应头中添加API版本信息 14 | options.ReportApiVersions = true; 15 | // 如果客户端不显式指定API版本,则使用默认版本 16 | options.AssumeDefaultVersionWhenUnspecified = true; 17 | // 配置默认版本为1.0 18 | options.DefaultApiVersion = new ApiVersion(1, 0); 19 | // 指定请求头中携带用于指定API版本信息的字段 20 | options.ApiVersionReader = new HeaderApiVersionReader("api-version"); 21 | // 使用Convention标记deprecated 22 | options.Conventions.Controller().HasDeprecatedApiVersion(new ApiVersion(2, 0)); 23 | }); 24 | } 25 | } -------------------------------------------------------------------------------- /src/TodoList.Api/Extensions/ExceptionMiddlewareExtensions.cs: -------------------------------------------------------------------------------- 1 | using TodoList.Api.Middlewares; 2 | 3 | namespace TodoList.Api.Extensions; 4 | 5 | public static class ExceptionMiddlewareExtensions 6 | { 7 | public static WebApplication UseGlobalExceptionHandler(this WebApplication app) 8 | { 9 | app.UseMiddleware(); 10 | return app; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/TodoList.Api/Extensions/RateLimitingServiceExtensions.cs: -------------------------------------------------------------------------------- 1 | using AspNetCoreRateLimit; 2 | 3 | namespace TodoList.Api.Extensions; 4 | 5 | public static class RateLimitingServiceExtensions 6 | { 7 | public static void ConfigureRateLimiting(this IServiceCollection services) 8 | { 9 | // 当然也可以使用Configuration的方式读取RateLimit规则 10 | var rateLimitRules = new List 11 | { 12 | new () 13 | { 14 | Endpoint = "*", 15 | Limit = 2, 16 | Period = "5m" 17 | } 18 | }; 19 | services.Configure(options => options.GeneralRules = rateLimitRules); 20 | 21 | // 使用内存作为存储 22 | services.AddSingleton(); 23 | services.AddSingleton(); 24 | services.AddSingleton(); 25 | services.AddSingleton(); 26 | } 27 | } -------------------------------------------------------------------------------- /src/TodoList.Api/Filters/LogFilterAttribute.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json; 2 | using Microsoft.AspNetCore.Mvc; 3 | using Microsoft.AspNetCore.Mvc.Filters; 4 | 5 | namespace TodoList.Api.Filters; 6 | 7 | public class LogFilterAttribute : IActionFilter 8 | { 9 | private readonly ILogger _logger; 10 | 11 | public LogFilterAttribute(ILogger logger) => _logger = logger; 12 | 13 | public void OnActionExecuting(ActionExecutingContext context) 14 | { 15 | var action = context.RouteData.Values["action"]; 16 | var controller = context.RouteData.Values["controller"]; 17 | 18 | // 获取名称包含Command的参数值 19 | var param = context.ActionArguments.SingleOrDefault(x => x.Value.ToString().Contains("Command")).Value; 20 | 21 | _logger.LogInformation($"Controller:{controller}, action: {action}, Incoming request: {JsonSerializer.Serialize(param)}"); 22 | } 23 | 24 | public void OnActionExecuted(ActionExecutedContext context) 25 | { 26 | var action = context.RouteData.Values["action"]; 27 | var controller = context.RouteData.Values["controller"]; 28 | 29 | // 需要先将Result转换为ObjectResult类型才能拿到Value值 30 | var result = (ObjectResult)context.Result!; 31 | 32 | _logger.LogInformation($"Controller:{controller}, action: {action}, Executing response: {JsonSerializer.Serialize(result.Value)}"); 33 | } 34 | } -------------------------------------------------------------------------------- /src/TodoList.Api/Middlewares/GlobalExceptionMiddleware.cs: -------------------------------------------------------------------------------- 1 | using System.Net; 2 | using TodoList.Api.Models; 3 | using TodoList.Application.Common.Exceptions; 4 | 5 | namespace TodoList.Api.Middlewares; 6 | 7 | public class GlobalExceptionMiddleware 8 | { 9 | private readonly RequestDelegate _next; 10 | 11 | public GlobalExceptionMiddleware(RequestDelegate next) 12 | { 13 | _next = next; 14 | } 15 | 16 | public async Task InvokeAsync(HttpContext context) 17 | { 18 | try 19 | { 20 | await _next(context); 21 | } 22 | catch (Exception exception) 23 | { 24 | // 你可以在这里进行相关的日志记录 25 | await HandleExceptionAsync(context, exception); 26 | } 27 | } 28 | 29 | private async Task HandleExceptionAsync(HttpContext context, Exception exception) 30 | { 31 | context.Response.ContentType = "application/json"; 32 | 33 | // 对于抛出异常来说,更好的方式是在Application层定义一些继承自Exception的自定义异常 34 | // 然后在这里进行判断,这里只是做了简单的演示 35 | context.Response.StatusCode = exception switch 36 | { 37 | ApplicationException => (int)HttpStatusCode.BadRequest, 38 | KeyNotFoundException => (int)HttpStatusCode.NotFound, 39 | _ => (int)HttpStatusCode.InternalServerError 40 | }; 41 | 42 | var responseModel = ApiResponse.Fail(exception.Message); 43 | 44 | await context.Response.WriteAsync(responseModel.ToJsonString()); 45 | } 46 | } -------------------------------------------------------------------------------- /src/TodoList.Api/Models/ApiResponse.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json; 2 | 3 | namespace TodoList.Api.Models; 4 | 5 | public class ApiResponse 6 | { 7 | public T Data { get; set; } 8 | public bool Succeeded { get; set; } 9 | public string Message { get; set; } 10 | public static ApiResponse Fail(string errorMessage) => new() { Succeeded = false, Message = errorMessage }; 11 | public static ApiResponse Success(T data) => new() { Succeeded = true, Data = data }; 12 | 13 | public string ToJsonString() => JsonSerializer.Serialize(this); 14 | } -------------------------------------------------------------------------------- /src/TodoList.Api/Models/ErrorResponse.cs: -------------------------------------------------------------------------------- 1 | using System.Net; 2 | using System.Text.Json; 3 | 4 | namespace TodoList.Api.Models; 5 | 6 | 7 | // 统一使用ApiResponse进行返回,该类不再继续使用 8 | [Obsolete] 9 | public class ErrorResponse 10 | { 11 | public HttpStatusCode StatusCode { get; set; } = HttpStatusCode.InternalServerError; 12 | public string Message { get; set; } = "An unexpected error occurred."; 13 | public string ToJsonString() => JsonSerializer.Serialize(this); 14 | } -------------------------------------------------------------------------------- /src/TodoList.Api/Program.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using Marvin.Cache.Headers; 3 | using Microsoft.AspNetCore.Diagnostics.HealthChecks; 4 | using Microsoft.AspNetCore.HttpLogging; 5 | using Microsoft.AspNetCore.Mvc; 6 | using Microsoft.OpenApi.Models; 7 | using TodoList.Api.Extensions; 8 | using TodoList.Api.Filters; 9 | using TodoList.Api.Services; 10 | using TodoList.Application; 11 | using TodoList.Application.Common.Interfaces; 12 | using TodoList.Infrastructure; 13 | using TodoList.Infrastructure.Log; 14 | 15 | var builder = WebApplication.CreateBuilder(args); 16 | 17 | // Add services to the container. 18 | builder.ConfigureLog(); 19 | builder.Services.ConfigureApiVersioning(); 20 | builder.Services.AddSingleton(); 21 | 22 | builder.Services.AddLocalization(options => options.ResourcesPath = "Resources"); 23 | builder.Services.AddResponseCaching(); 24 | builder.Services.AddHttpCacheHeaders( 25 | expirationOptions => 26 | { 27 | expirationOptions.MaxAge = 180; 28 | expirationOptions.CacheLocation = CacheLocation.Private; 29 | }, 30 | validateOptions => 31 | { 32 | validateOptions.MustRevalidate = true; 33 | }); 34 | builder.Services.AddMemoryCache(); 35 | builder.Services.ConfigureRateLimiting(); 36 | builder.Services.AddHttpContextAccessor(); 37 | builder.Services.AddControllers(options => 38 | { 39 | options.CacheProfiles.Add("60SecondDuration", new CacheProfile { Duration = 60 }); 40 | }); 41 | builder.Services.AddHttpLogging(options => 42 | { 43 | // 日志记录的字段配置,可以以 | 连接 44 | options.LoggingFields = HttpLoggingFields.All; 45 | // 增加请求头字段记录 46 | options.RequestHeaders.Add("Sec-Fetch-Site"); 47 | options.RequestHeaders.Add("Sec-Fetch-Mode"); 48 | options.RequestHeaders.Add("Sec-Fetch-Dest"); 49 | // 增加响应头字段记录 50 | options.ResponseHeaders.Add("Server"); 51 | // 增加请求的媒体类型 52 | options.MediaTypeOptions.AddText("application/javascript"); 53 | // 配置请求体日志最大长度 54 | options.RequestBodyLogLimit = 4096; 55 | // 配置响应体日志最大长度 56 | options.ResponseBodyLogLimit = 4096; 57 | }); 58 | builder.Services.AddEndpointsApiExplorer(); 59 | builder.Services.AddSwaggerGen(s => 60 | { 61 | s.SwaggerDoc("1.0", new OpenApiInfo { Title = "TodoList API", Version = "1.0"}); 62 | s.SwaggerDoc("2.0", new OpenApiInfo { Title = "TodoList API", Version = "2.0"}); 63 | 64 | var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; 65 | var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); 66 | s.IncludeXmlComments(xmlPath); 67 | 68 | s.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme 69 | { 70 | In = ParameterLocation.Header, 71 | Description = "Add JWT with Bearer", 72 | Name = "Authorization", 73 | Type = SecuritySchemeType.ApiKey, 74 | Scheme = "Bearer" 75 | }); 76 | 77 | s.AddSecurityRequirement(new OpenApiSecurityRequirement 78 | { 79 | { 80 | new OpenApiSecurityScheme 81 | { 82 | Reference = new OpenApiReference 83 | { 84 | Type = ReferenceType.SecurityScheme, 85 | Id = "Bearer" 86 | }, 87 | Name = "Bearer" 88 | }, 89 | new List() 90 | } 91 | }); 92 | }); 93 | 94 | builder.Services.AddScoped(); 95 | 96 | // 添加应用层配置 97 | builder.Services.AddApplication(); 98 | // 添加基础设施配置 99 | builder.Services.AddInfrastructure(builder.Configuration); 100 | 101 | var app = builder.Build(); 102 | 103 | app.UseGlobalExceptionHandler(); 104 | // Configure the HTTP request pipeline. 105 | 106 | app.UseHttpsRedirection(); 107 | app.UseRouting(); 108 | // app.UseIpRateLimiting(); 109 | 110 | app.UseAuthentication(); 111 | app.UseAuthorization(); 112 | 113 | if (app.Environment.IsDevelopment()) 114 | { 115 | app.UseSwagger(); 116 | app.UseSwaggerUI(s => 117 | { 118 | s.SwaggerEndpoint("/swagger/1.0/swagger.json", "TodoList API v1.0"); 119 | s.SwaggerEndpoint("/swagger/2.0/swagger.json", "TodoList API v2.0"); 120 | }); 121 | } 122 | 123 | app.UseHttpLogging(); 124 | // app.UseResponseCaching(); 125 | // app.UseHttpCacheHeaders(); 126 | var supportedCultures = new[] { "en-US", "zh" }; 127 | var localizationOptions = new RequestLocalizationOptions() 128 | .SetDefaultCulture(supportedCultures[0]) 129 | .AddSupportedCultures(supportedCultures) 130 | .AddSupportedUICultures(supportedCultures); 131 | 132 | app.UseRequestLocalization(localizationOptions); 133 | 134 | app.MapDefaultControllerRoute(); 135 | app.MapHealthChecks("/ready", new HealthCheckOptions { Predicate = _ => false }); 136 | app.MapHealthChecks("/liveness", new HealthCheckOptions { Predicate = r => r.Name.Contains("self") }); 137 | app.MapHealthChecks("/hc"); 138 | 139 | app.MigrateDatabase(); 140 | 141 | app.Run(); -------------------------------------------------------------------------------- /src/TodoList.Api/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:16384", 8 | "sslPort": 44317 9 | } 10 | }, 11 | "profiles": { 12 | "TodoList.Api": { 13 | "commandName": "Project", 14 | "dotnetRunMessages": true, 15 | "launchBrowser": true, 16 | "launchUrl": "swagger", 17 | "applicationUrl": "https://localhost:7039;http://localhost:5050", 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 | -------------------------------------------------------------------------------- /src/TodoList.Api/Resources/Controllers.TodoListController.en-us.Designer.cs: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This code was generated by a tool. 4 | // 5 | // Changes to this file may cause incorrect behavior and will be lost if 6 | // the code is regenerated. 7 | // 8 | //------------------------------------------------------------------------------ 9 | 10 | namespace TodoList.Api.Resources { 11 | using System; 12 | 13 | 14 | [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] 15 | [System.Diagnostics.DebuggerNonUserCodeAttribute()] 16 | [System.Runtime.CompilerServices.CompilerGeneratedAttribute()] 17 | internal class Controllers_TodoListController_en_us { 18 | 19 | private static System.Resources.ResourceManager resourceMan; 20 | 21 | private static System.Globalization.CultureInfo resourceCulture; 22 | 23 | [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] 24 | internal Controllers_TodoListController_en_us() { 25 | } 26 | 27 | [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] 28 | internal static System.Resources.ResourceManager ResourceManager { 29 | get { 30 | if (object.Equals(null, resourceMan)) { 31 | System.Resources.ResourceManager temp = new System.Resources.ResourceManager("TodoList.Api.Resources.Controllers_TodoListController_en_us", typeof(Controllers_TodoListController_en_us).Assembly); 32 | resourceMan = temp; 33 | } 34 | return resourceMan; 35 | } 36 | } 37 | 38 | [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] 39 | internal static System.Globalization.CultureInfo Culture { 40 | get { 41 | return resourceCulture; 42 | } 43 | set { 44 | resourceCulture = value; 45 | } 46 | } 47 | 48 | internal static string TodoListMeta { 49 | get { 50 | return ResourceManager.GetString("TodoListMeta", resourceCulture); 51 | } 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/TodoList.Api/Resources/Controllers.TodoListController.en-us.resx: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | text/microsoft-resx 11 | 12 | 13 | 1.3 14 | 15 | 16 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 17 | 18 | 19 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 20 | 21 | 22 | This is a TodoList Controller 23 | 24 | -------------------------------------------------------------------------------- /src/TodoList.Api/Resources/Controllers.TodoListController.zh.Designer.cs: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This code was generated by a tool. 4 | // 5 | // Changes to this file may cause incorrect behavior and will be lost if 6 | // the code is regenerated. 7 | // 8 | //------------------------------------------------------------------------------ 9 | 10 | namespace TodoList.Api.Resources { 11 | using System; 12 | 13 | 14 | [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] 15 | [System.Diagnostics.DebuggerNonUserCodeAttribute()] 16 | [System.Runtime.CompilerServices.CompilerGeneratedAttribute()] 17 | internal class Controllers_TodoListController_zh { 18 | 19 | private static System.Resources.ResourceManager resourceMan; 20 | 21 | private static System.Globalization.CultureInfo resourceCulture; 22 | 23 | [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] 24 | internal Controllers_TodoListController_zh() { 25 | } 26 | 27 | [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] 28 | internal static System.Resources.ResourceManager ResourceManager { 29 | get { 30 | if (object.Equals(null, resourceMan)) { 31 | System.Resources.ResourceManager temp = new System.Resources.ResourceManager("TodoList.Api.Resources.Controllers_TodoListController_zh", typeof(Controllers_TodoListController_zh).Assembly); 32 | resourceMan = temp; 33 | } 34 | return resourceMan; 35 | } 36 | } 37 | 38 | [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] 39 | internal static System.Globalization.CultureInfo Culture { 40 | get { 41 | return resourceCulture; 42 | } 43 | set { 44 | resourceCulture = value; 45 | } 46 | } 47 | 48 | internal static string TodoListMeta { 49 | get { 50 | return ResourceManager.GetString("TodoListMeta", resourceCulture); 51 | } 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/TodoList.Api/Resources/Controllers.TodoListController.zh.resx: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | text/microsoft-resx 11 | 12 | 13 | 1.3 14 | 15 | 16 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 17 | 18 | 19 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 20 | 21 | 22 | 这是一个TodoList应用控制器 23 | 24 | -------------------------------------------------------------------------------- /src/TodoList.Api/Services/CurrentUserService.cs: -------------------------------------------------------------------------------- 1 | using System.Security.Claims; 2 | using TodoList.Application.Common.Interfaces; 3 | 4 | namespace TodoList.Api.Services; 5 | 6 | public class CurrentUserService : ICurrentUserService 7 | { 8 | private readonly IHttpContextAccessor _httpContextAccessor; 9 | 10 | public CurrentUserService(IHttpContextAccessor httpContextAccessor) 11 | { 12 | _httpContextAccessor = httpContextAccessor; 13 | } 14 | 15 | public string? UserName => _httpContextAccessor.HttpContext?.User.FindFirstValue(ClaimTypes.Name); 16 | } -------------------------------------------------------------------------------- /src/TodoList.Api/TodoList.Api.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | Linux 8 | 9 | 10 | 11 | TodoList.Api.xml 12 | 13 | 1701;1702;1591 14 | 15 | 16 | 17 | TodoList.Api.xml 18 | 19 | 1701;1702;1591 20 | 21 | 22 | 23 | aspnetcore.pfx 24 | 25 | 1701;1702;1591 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | all 36 | runtime; build; native; contentfiles; analyzers; buildtransitive 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | ResXFileCodeGenerator 49 | Controllers.TodoListController.en-us.Designer.cs 50 | 51 | 52 | ResXFileCodeGenerator 53 | Controllers.TodoListController.zh.Designer.cs 54 | 55 | 56 | 57 | 58 | 59 | True 60 | True 61 | Controllers.TodoListController.en.resx 62 | 63 | 64 | True 65 | True 66 | Controllers.TodoListController.zh.resx 67 | 68 | 69 | 70 | 71 | -------------------------------------------------------------------------------- /src/TodoList.Api/TodoList.Api.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | TodoList.Api 5 | 6 | 7 | 8 | 9 | 创建新的TodoList,只有Administrator角色的用户有此权限 10 | 11 | 创建TodoList命令 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /src/TodoList.Api/WeatherForecast.cs: -------------------------------------------------------------------------------- 1 | namespace TodoList.Api; 2 | 3 | public class WeatherForecast 4 | { 5 | public DateTime Date { get; set; } 6 | 7 | public int TemperatureC { get; set; } 8 | 9 | public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); 10 | 11 | public string? Summary { get; set; } 12 | } 13 | -------------------------------------------------------------------------------- /src/TodoList.Api/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | }, 8 | "UseFileToLog": true, 9 | "ConnectionStrings": { 10 | "SqlServerConnection": "Server=localhost,1433;Database=TodoListDb;User Id=sa;Password=StrongPwd123;" 11 | }, 12 | "JwtSettings": { 13 | "validIssuer": "TodoListApi", 14 | "validAudience": "http://localhost:5050", 15 | "expires": 5 16 | }, 17 | "JwtApiV2Settings": { 18 | "validIssuer": "TodoListApiV2", 19 | "validAudience": "http://localhost:5050", 20 | "expires": 10 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/TodoList.Api/appsettings.Production.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | }, 8 | "UseFileToLog": true, 9 | "ConnectionStrings": { 10 | "SqlServerConnection": "Server=tcp:code4nothing.database.windows.net,1433;Initial Catalog=TodoListDb;Persist Security Info=False;User ID=code4nothing;Password=TestTodo@123;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;" 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/TodoList.Api/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | }, 8 | "UseFileToLog": false, 9 | "AllowedHosts": "*" 10 | } 11 | -------------------------------------------------------------------------------- /src/TodoList.Api/aspnetapp.pfx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Asinta/TodoList/41c7d9ef542e80426498fb1b8e0f2164786925f7/src/TodoList.Api/aspnetapp.pfx -------------------------------------------------------------------------------- /src/TodoList.Api/tempkey.jwk: -------------------------------------------------------------------------------- 1 | {"AdditionalData":{},"Alg":"RS256","Crv":null,"D":"ANQejYZaBI7-7oyytyxW1X0aiOSnRnB94ueJtRL8ILZrUqpNpVlZeAUC-UG9_rgjWk7BWiSs4ob4e_pz5zHhytBFy2MnevLGfPXizTZ-Lp39sK3qvWtAcRBXGmfN0YZgVXuRM76JGZoc4CLiCIplb4Jr5CJqeYS5w-AuWPbHNVR1589cv_3rEuTx9nGIINrrH-WcNFqGABX1hsF1iePN1Kd9JGr1ULJsvtlKqQNZTyBf6ym1Q5gCRhDeWlPI-kmue7wvD2KjBDCyHnb_5MC8uk9FtOQxvFYV_jM7PwDuHmDYuaT5zF-W06idXUk2dRo3Ed0Kxc0kVAh17KxY-dbJsQ","DP":"ovPdtE2nCs4pltFpKDh6ohDPbPxTTvSHPgLFkXkOl_IUZch4UaGyhGFOUAjJdSm18FvXtL1MEq5IGCCgQGAxpp2hhXQc-8Qzax08Gclo2yUwsaBsr4v357_vbIeZ611rQMlJyDYKCxDn7AfHigJCOvont8YCtdtNdd-53OwfMqc","DQ":"tkTKoiDmj5dsWjhSW61z80f1m4TQ0M2Taf3us41f-AFVJwD30djgzhliRmMBMbpGf-YfeBWlPI7bUr2FTv9t78Wn4t0dORuKwJJH_t7cc7sbUFfu5Jr1mMAtC-gekehmrKO_kvGKiGE_GRI77c0luoPZ3VDp-bQSLxKM2Lli9UU","E":"AQAB","K":null,"KeyId":"72A690ED4CE1BE9A32F86EF0C4B9EBDC","KeyOps":[],"Kid":"72A690ED4CE1BE9A32F86EF0C4B9EBDC","Kty":"RSA","N":"5CpcHxcsARcdoPJNTpRx1OhcgDPPsk3LuGOds0yWQ0cHnsqNm_YflxriK8uQoXzZwbrLL1t1din2Q7JtVdG76GfqHyNadpgiItKRUP0yrEl5MQ5vJra1C5jrSh5byEbW-XCaJnDGEF0Ekgai4DF0EQ5qAntG68dL8OIfWWmY2xRt2AWri86Auv5xlvCzMkmYoaFgZcCp86rxjZNxzUy54yxL73bw5lqT4z34JCLE1Cup5w36skONQ_ccxsXWRVCkIjcJ1yo8TKhhd8rTZqYrrSXgx0aMmZAJh-buQ_i4SIuXWSHrHmsSLWUbA77UnKGhPFBlTJWemZd7Lm-X0bvbiw","Oth":null,"P":"_QNSUnHJ4-0UVHfSNOKVZdXChfnBOOhOFbaGfPGoEytvF8MYZnzIjDLj2Rr6-MV_QFrhE-rsO91AfgMSO0hWjaOU3Hyju0coCAKEr3WJ5HcFC4Y6SPdzdXLo3Vgro0wy9bkXPow_-x4IuivS0GTmVYgiaabShG_JeFsrGJ4zoWc","Q":"5tvxId0QX7HtfpX7dUpGgYQWrUjLbjzip3DhnVtGS98xlztR65cGzDwk3iuQ3MGReRqPZnQ5V8ZKm1OwDO01fmHzEdnGnBksHiAr8JPtglIYNeJ_wfyoDmVsYEPQLWS4QEpQHSL2Kzr8n1Y5vOMb6tAGk3rULELFc59YPE_Aqj0","QI":"Foa9_LbH83DWNqhGBg2zONVsgAnIMYTpMwT5j_LT2eiHLGc0weQAPOkRD6jDunqfQPiz4em_MCkEdgUB2j_yDGwp11rg_tyG9OZVcW7B74M0lgPVTpCo1E-Ah798GtzevxbYWUZmxMqm2r74YV1Zg2fYWjy3YTwiXKdCwBV78ZM","Use":null,"X":null,"X5c":[],"X5t":null,"X5tS256":null,"X5u":null,"Y":null,"KeySize":2048,"HasPrivateKey":true,"CryptoProviderFactory":{"CryptoProviderCache":{},"CustomCryptoProvider":null,"CacheSignatureProviders":true,"SignatureProviderObjectPoolCacheSize":48}} -------------------------------------------------------------------------------- /src/TodoList.Application/Common/ApplicationHealthCheck.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Diagnostics.HealthChecks; 2 | 3 | namespace TodoList.Application.Common; 4 | 5 | public class ApplicationHealthCheck : IHealthCheck 6 | { 7 | private static readonly Random _rnd = new (); 8 | 9 | public Task CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default) 10 | { 11 | var result = _rnd.Next(5) == 0 12 | ? HealthCheckResult.Healthy() 13 | : HealthCheckResult.Unhealthy("Failed random"); 14 | 15 | return Task.FromResult(result); 16 | } 17 | } -------------------------------------------------------------------------------- /src/TodoList.Application/Common/Behaviors/LoggingBehavior.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using MediatR.Pipeline; 3 | using Microsoft.Extensions.Logging; 4 | 5 | public class LoggingBehaviour : IRequestPreProcessor where TRequest : notnull 6 | { 7 | private readonly ILogger> _logger; 8 | 9 | // 在构造函数中后面我们还可以注入类似ICurrentUser和IIdentity相关的对象进行日志输出 10 | public LoggingBehaviour(ILogger> logger) 11 | { 12 | _logger = logger; 13 | } 14 | 15 | public async Task Process(TRequest request, CancellationToken cancellationToken) 16 | { 17 | // 你可以在这里log关于请求的任何信息 18 | _logger.LogInformation($"Handling {typeof(TRequest).Name}"); 19 | 20 | IList props = new List(request.GetType().GetProperties()); 21 | foreach (var prop in props) 22 | { 23 | var propValue = prop.GetValue(request, null); 24 | _logger.LogInformation("{Property} : {@Value}", prop.Name, propValue); 25 | } 26 | } 27 | } -------------------------------------------------------------------------------- /src/TodoList.Application/Common/Behaviors/ValidationBehavior.cs: -------------------------------------------------------------------------------- 1 | using FluentValidation; 2 | using FluentValidation.Results; 3 | using MediatR; 4 | using ValidationException = TodoList.Application.Common.Exceptions.ValidationException; 5 | 6 | namespace TodoList.Application.Common.Behaviors; 7 | 8 | public class ValidationBehaviour : IPipelineBehavior 9 | where TRequest : notnull 10 | { 11 | private readonly IEnumerable> _validators; 12 | 13 | // 注入所有自定义的Validators 14 | public ValidationBehaviour(IEnumerable> validators) 15 | => _validators = validators; 16 | 17 | public async Task Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate next) 18 | { 19 | if (_validators.Any()) 20 | { 21 | var context = new ValidationContext(request); 22 | 23 | var validationResults = await Task.WhenAll(_validators.Select(v => v.ValidateAsync(context, cancellationToken))); 24 | 25 | var failures = validationResults 26 | .Where(r => r.Errors.Any()) 27 | .SelectMany(r => r.Errors) 28 | .ToList(); 29 | 30 | // 如果有validator校验失败,抛出异常,这里的异常是我们自定义的包装类型 31 | if (failures.Any()) 32 | throw new ValidationException(GetValidationErrorMessage(failures)); 33 | } 34 | return await next(); 35 | } 36 | 37 | // 格式化校验失败消息 38 | private string GetValidationErrorMessage(IEnumerable failures) 39 | { 40 | var failureDict = failures 41 | .GroupBy(e => e.PropertyName, e => e.ErrorMessage) 42 | .ToDictionary(failureGroup => failureGroup.Key, failureGroup => failureGroup.ToArray()); 43 | 44 | return string.Join(";", failureDict.Select(kv => kv.Key + ": " + string.Join(' ', kv.Value.ToArray()))); 45 | } 46 | } -------------------------------------------------------------------------------- /src/TodoList.Application/Common/Configurations/JwtConfiguration.cs: -------------------------------------------------------------------------------- 1 | namespace TodoList.Application.Common.Configurations; 2 | 3 | public class JwtConfiguration 4 | { 5 | public string Section { get; set; } = "JwtSettings"; 6 | public string? ValidIssuer { get; set; } 7 | public string? ValidAudience { get; set; } 8 | public string? Expires { get; set; } 9 | } -------------------------------------------------------------------------------- /src/TodoList.Application/Common/DataShaper.cs: -------------------------------------------------------------------------------- 1 | using System.Dynamic; 2 | using System.Reflection; 3 | using TodoList.Application.Common.Interfaces; 4 | 5 | namespace TodoList.Application.Common; 6 | 7 | public class DataShaper : IDataShaper where T : class 8 | { 9 | public PropertyInfo[] Properties { get; set; } 10 | 11 | public DataShaper() 12 | { 13 | Properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); 14 | } 15 | 16 | public IEnumerable ShapeData(IEnumerable entities, string? fieldString) 17 | { 18 | var requiredProperties = GetRequiredProperties(fieldString); 19 | 20 | return GetData(entities, requiredProperties); 21 | } 22 | 23 | public ExpandoObject ShapeData(T entity, string? fieldString) 24 | { 25 | var requiredProperties = GetRequiredProperties(fieldString); 26 | 27 | return GetDataForEntity(entity, requiredProperties); 28 | } 29 | 30 | private IEnumerable GetRequiredProperties(string? fieldString) 31 | { 32 | var requiredProperties = new List(); 33 | 34 | if (!string.IsNullOrEmpty(fieldString)) 35 | { 36 | var fields = fieldString.Split(',', StringSplitOptions.RemoveEmptyEntries); 37 | foreach (var field in fields) 38 | { 39 | var property = Properties.FirstOrDefault(pi => pi.Name.Equals(field.Trim(), StringComparison.InvariantCultureIgnoreCase)); 40 | if (property == null) 41 | { 42 | continue; 43 | } 44 | 45 | requiredProperties.Add(property); 46 | } 47 | } 48 | else 49 | { 50 | requiredProperties = Properties.ToList(); 51 | } 52 | 53 | return requiredProperties; 54 | } 55 | 56 | private IEnumerable GetData(IEnumerable entities, IEnumerable requiredProperties) 57 | { 58 | return entities.Select(entity => GetDataForEntity(entity, requiredProperties)).ToList(); 59 | } 60 | 61 | private ExpandoObject GetDataForEntity(T entity, IEnumerable requiredProperties) 62 | { 63 | var shapedObject = new ExpandoObject(); 64 | foreach (var property in requiredProperties) 65 | { 66 | var objectPropertyValue = property.GetValue(entity); 67 | shapedObject.TryAdd(property.Name, objectPropertyValue); 68 | } 69 | 70 | return shapedObject; 71 | } 72 | } -------------------------------------------------------------------------------- /src/TodoList.Application/Common/Exceptions/NotFoundException.cs: -------------------------------------------------------------------------------- 1 | namespace TodoList.Application.Common.Exceptions; 2 | 3 | public class NotFoundException : Exception 4 | { 5 | public NotFoundException() 6 | : base() 7 | { 8 | } 9 | 10 | public NotFoundException(string message) 11 | : base(message) 12 | { 13 | } 14 | 15 | public NotFoundException(string message, Exception innerException) 16 | : base(message, innerException) 17 | { 18 | } 19 | 20 | public NotFoundException(string name, object key) 21 | : base($"Entity \"{name}\" ({key}) was not found.") 22 | { 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/TodoList.Application/Common/Exceptions/ValidationException.cs: -------------------------------------------------------------------------------- 1 | namespace TodoList.Application.Common.Exceptions; 2 | 3 | public class ValidationException : Exception 4 | { 5 | public ValidationException() : base("One or more validation failures have occurred.") 6 | { 7 | } 8 | 9 | public ValidationException(string failures) 10 | : base(failures) 11 | { 12 | } 13 | } -------------------------------------------------------------------------------- /src/TodoList.Application/Common/Extensions/DataShaperExtensions.cs: -------------------------------------------------------------------------------- 1 | using System.Dynamic; 2 | using TodoList.Application.Common.Interfaces; 3 | 4 | namespace TodoList.Application.Common.Extensions; 5 | 6 | public static class DataShaperExtensions 7 | { 8 | public static IEnumerable ShapeData(this IEnumerable entities, IDataShaper shaper, string? fieldString) 9 | { 10 | return shaper.ShapeData(entities, fieldString); 11 | } 12 | } -------------------------------------------------------------------------------- /src/TodoList.Application/Common/Interfaces/IApplicationDbContext.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using TodoList.Domain.Entities; 3 | 4 | namespace TodoList.Application.Common.Interfaces; 5 | public interface IApplicationDbContext 6 | { 7 | DbSet TodoLists { get; } 8 | DbSet TodoItems { get; } 9 | Task SaveChangesAsync(CancellationToken cancellationToken); 10 | } -------------------------------------------------------------------------------- /src/TodoList.Application/Common/Interfaces/ICurrentUserService.cs: -------------------------------------------------------------------------------- 1 | namespace TodoList.Application.Common.Interfaces; 2 | 3 | public interface ICurrentUserService 4 | { 5 | string? UserName { get; } 6 | } -------------------------------------------------------------------------------- /src/TodoList.Application/Common/Interfaces/IDataShaper.cs: -------------------------------------------------------------------------------- 1 | using System.Dynamic; 2 | 3 | namespace TodoList.Application.Common.Interfaces; 4 | 5 | public interface IDataShaper 6 | { 7 | IEnumerable ShapeData(IEnumerable entities, string? fieldString); 8 | ExpandoObject ShapeData(T entity, string? fieldString); 9 | } -------------------------------------------------------------------------------- /src/TodoList.Application/Common/Interfaces/IDomainEventService.cs: -------------------------------------------------------------------------------- 1 | using TodoList.Domain.Base; 2 | 3 | namespace TodoList.Application.Common.Interfaces; 4 | 5 | public interface IDomainEventService 6 | { 7 | Task Publish(DomainEvent domainEvent); 8 | } 9 | -------------------------------------------------------------------------------- /src/TodoList.Application/Common/Interfaces/IIdentityService.cs: -------------------------------------------------------------------------------- 1 | using TodoList.Application.Common.Models; 2 | 3 | namespace TodoList.Application.Common.Interfaces; 4 | 5 | public interface IIdentityService 6 | { 7 | // 出于演示的目的,只定义以下方法,实际使用的认证服务会提供更多的方法 8 | Task CreateUserAsync(string userName, string password); 9 | Task ValidateUserAsync(UserForAuthentication userForAuthentication); 10 | Task CreateTokenAsync(bool populateExpiry); 11 | Task RefreshTokenAsync(ApplicationToken token); 12 | } -------------------------------------------------------------------------------- /src/TodoList.Application/Common/Interfaces/IRepository.cs: -------------------------------------------------------------------------------- 1 | using System.Linq.Expressions; 2 | 3 | namespace TodoList.Application.Common.Interfaces; 4 | 5 | public interface IRepository where T : class 6 | { 7 | // 1. 查询基础操作接口 8 | IQueryable GetAsQueryable(); 9 | IQueryable GetAsQueryable(ISpecification spec); 10 | IQueryable GetAsQueryable(Expression> condition); 11 | 12 | // 2. 查询数量相关接口 13 | int Count(ISpecification? spec = null); 14 | int Count(Expression> condition); 15 | Task CountAsync(ISpecification? spec); 16 | 17 | // 3. 查询存在性相关接口 18 | bool Any(ISpecification? spec); 19 | bool Any(Expression>? condition = null); 20 | 21 | // 4. 根据条件获取原始实体类型数据相关接口 22 | ValueTask GetAsync(object key); 23 | Task GetAsync(Expression> condition); 24 | Task> GetAsync(); 25 | Task> GetAsync(ISpecification? spec); 26 | 27 | // 5. 根据条件获取映射实体类型数据相关接口,涉及到Group相关操作也在其中 28 | TResult? SelectFirstOrDefault(ISpecification? spec, Expression> selector); 29 | Task SelectFirstOrDefaultAsync(ISpecification? spec, Expression> selector); 30 | Task> SelectAsync(Expression> selector); 31 | Task> SelectAsync(ISpecification? spec, Expression> selector); 32 | Task> SelectAsync(Expression> groupExpression, Expression, TResult>> selector, ISpecification? spec = null); 33 | 34 | // Create相关操作接口 35 | Task AddAsync(T entity, CancellationToken cancellationToken = default); 36 | 37 | // Update相关操作接口 38 | Task UpdateAsync(T entity, CancellationToken cancellationToken = default); 39 | 40 | // Delete相关操作接口 41 | Task DeleteAsync(object key); 42 | Task DeleteAsync(T entity, CancellationToken cancellationToken = default); 43 | Task DeleteRangeAsync(IEnumerable entities, CancellationToken cancellationToken = default); 44 | 45 | Task SaveChangesAsync(CancellationToken cancellationToken = default); 46 | } -------------------------------------------------------------------------------- /src/TodoList.Application/Common/Interfaces/ISpecification.cs: -------------------------------------------------------------------------------- 1 | using System.Linq.Expressions; 2 | using Microsoft.EntityFrameworkCore.Query; 3 | 4 | namespace TodoList.Application.Common.Interfaces; 5 | 6 | public interface ISpecification 7 | { 8 | // 查询条件子句 9 | Expression> Criteria { get; } 10 | // Include子句 11 | Func, IIncludableQueryable> Include { get; } 12 | // OrderBy子句 13 | Expression> OrderBy { get; } 14 | // OrderByDescending子句 15 | Expression> OrderByDescending { get; } 16 | 17 | // 分页相关属性 18 | int Take { get; } 19 | int Skip { get; } 20 | bool IsPagingEnabled { get; } 21 | } 22 | -------------------------------------------------------------------------------- /src/TodoList.Application/Common/Mappings/IMapFrom.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | 3 | namespace TodoList.Application.Common.Mappings; 4 | 5 | public interface IMapFrom 6 | { 7 | void Mapping(Profile profile) => profile.CreateMap(typeof(T), GetType()); 8 | } -------------------------------------------------------------------------------- /src/TodoList.Application/Common/Mappings/MappingExtensions.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using AutoMapper.QueryableExtensions; 3 | using Microsoft.EntityFrameworkCore; 4 | using TodoList.Application.Common.Models; 5 | 6 | namespace TodoList.Application.Common.Mappings; 7 | 8 | public static class MappingExtensions 9 | { 10 | public static Task> PaginatedListAsync(this IQueryable queryable, int pageNumber, int pageSize) 11 | { 12 | return PaginatedList.CreateAsync(queryable, pageNumber, pageSize); 13 | } 14 | 15 | public static Task> ProjectToListAsync(this IQueryable queryable, IConfigurationProvider configuration) 16 | { 17 | return queryable.ProjectTo(configuration).ToListAsync(); 18 | } 19 | 20 | public static PaginatedList PaginatedListFromEnumerable(this IEnumerable entities, int pageNumber, int pageSize) 21 | { 22 | return PaginatedList.Create(entities, pageNumber, pageSize); 23 | } 24 | } -------------------------------------------------------------------------------- /src/TodoList.Application/Common/Mappings/MappingProfile.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using AutoMapper; 3 | 4 | namespace TodoList.Application.Common.Mappings; 5 | 6 | public class MappingProfile : Profile 7 | { 8 | public MappingProfile() => ApplyMappingsFromAssembly(Assembly.GetExecutingAssembly()); 9 | 10 | private void ApplyMappingsFromAssembly(Assembly assembly) 11 | { 12 | var types = assembly.GetExportedTypes() 13 | .Where(t => t.GetInterfaces().Any(i => 14 | i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IMapFrom<>))) 15 | .ToList(); 16 | 17 | foreach (var type in types) 18 | { 19 | var instance = Activator.CreateInstance(type); 20 | 21 | var methodInfo = type.GetMethod("Mapping") 22 | ?? type.GetInterface("IMapFrom`1")!.GetMethod("Mapping"); 23 | 24 | methodInfo?.Invoke(instance, new object[] { this }); 25 | } 26 | } 27 | } -------------------------------------------------------------------------------- /src/TodoList.Application/Common/Models/ApplicationToken.cs: -------------------------------------------------------------------------------- 1 | namespace TodoList.Application.Common.Models; 2 | 3 | public record ApplicationToken(string AccessToken, string RefreshToken); -------------------------------------------------------------------------------- /src/TodoList.Application/Common/Models/DomainEventNotification.cs: -------------------------------------------------------------------------------- 1 | using MediatR; 2 | using TodoList.Domain.Base; 3 | 4 | namespace TodoList.Application.Common.Models; 5 | 6 | public class DomainEventNotification : INotification where TDomainEvent : DomainEvent 7 | { 8 | public DomainEventNotification(TDomainEvent domainEvent) 9 | { 10 | DomainEvent = domainEvent; 11 | } 12 | 13 | public TDomainEvent DomainEvent { get; } 14 | } -------------------------------------------------------------------------------- /src/TodoList.Application/Common/Models/Link.cs: -------------------------------------------------------------------------------- 1 | namespace TodoList.Application.Common.Models; 2 | 3 | public class Link 4 | { 5 | public string? Href { get; set; } 6 | public string? Rel { get; set; } 7 | public string? Method { get; set; } 8 | 9 | public Link() 10 | { 11 | } 12 | 13 | public Link(string href, string rel, string method) 14 | { 15 | Href = href; 16 | Rel = rel; 17 | Method = method; 18 | } 19 | } -------------------------------------------------------------------------------- /src/TodoList.Application/Common/Models/LinkCollectionWrapper.cs: -------------------------------------------------------------------------------- 1 | namespace TodoList.Application.Common.Models; 2 | 3 | public class LinkCollectionWrapper : LinkResourceBase 4 | { 5 | public List Value { get; set; } = new (); 6 | 7 | public LinkCollectionWrapper() 8 | { 9 | } 10 | 11 | public LinkCollectionWrapper(List value) => Value = value; 12 | 13 | } -------------------------------------------------------------------------------- /src/TodoList.Application/Common/Models/LinkResourceBase.cs: -------------------------------------------------------------------------------- 1 | namespace TodoList.Application.Common.Models; 2 | 3 | public class LinkResourceBase 4 | { 5 | public LinkResourceBase() 6 | { 7 | } 8 | 9 | public List Links { get; set; } = new (); 10 | } -------------------------------------------------------------------------------- /src/TodoList.Application/Common/Models/PaginatedList.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | 3 | namespace TodoList.Application.Common.Models; 4 | 5 | public class PaginatedList 6 | { 7 | public List Items { get; } 8 | public int PageNumber { get; } 9 | public int TotalPages { get; } 10 | public int TotalCount { get; } 11 | 12 | public PaginatedList(List items, int count, int pageNumber, int pageSize) 13 | { 14 | PageNumber = pageNumber; 15 | TotalPages = (int)Math.Ceiling(count / (double)pageSize); 16 | TotalCount = count; 17 | Items = items; 18 | } 19 | 20 | // 增加属性表示是否有前一页 21 | public bool HasPreviousPage => PageNumber > 1; 22 | // 增加属性表示是否有后一页 23 | public bool HasNextPage => PageNumber < TotalPages; 24 | 25 | // 分页结果构建辅助方法 26 | public static async Task> CreateAsync(IQueryable source, int pageNumber, int pageSize) 27 | { 28 | var count = await source.CountAsync(); 29 | // 注意我们给的请求中pageNumber是从1开始的 30 | var items = await source.Skip((pageNumber - 1) * pageSize).Take(pageSize).ToListAsync(); 31 | 32 | return new PaginatedList(items, count, pageNumber, pageSize); 33 | } 34 | 35 | public static PaginatedList Create(IEnumerable source, int pageNumber, int pageSize) 36 | { 37 | var count = source.Count(); 38 | // 注意我们给的请求中pageNumber是从1开始的 39 | var items = source.Skip((pageNumber - 1) * pageSize).Take(pageSize).ToList(); 40 | 41 | return new PaginatedList(items, count, pageNumber, pageSize); 42 | } 43 | } -------------------------------------------------------------------------------- /src/TodoList.Application/Common/Models/ShapedEntity.cs: -------------------------------------------------------------------------------- 1 | using TodoList.Domain.Base.Interfaces; 2 | 3 | namespace TodoList.Application.Common.Models; 4 | 5 | public class ShapedEntity 6 | { 7 | public TKey Id { get; set; } 8 | public IEntity Entity { get; set; } 9 | 10 | public ShapedEntity() 11 | { 12 | } 13 | } -------------------------------------------------------------------------------- /src/TodoList.Application/Common/Models/UserForAuthentication.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | 3 | namespace TodoList.Application.Common.Models; 4 | 5 | public record UserForAuthentication 6 | { 7 | [Required(ErrorMessage = "username is required")] 8 | public string? UserName { get; set; } 9 | 10 | [Required(ErrorMessage = "password is required")] 11 | public string? Password { get; set; } 12 | } -------------------------------------------------------------------------------- /src/TodoList.Application/Common/SpecificationBase.cs: -------------------------------------------------------------------------------- 1 | using System.Linq.Expressions; 2 | using Microsoft.EntityFrameworkCore.Query; 3 | using TodoList.Application.Common.Interfaces; 4 | 5 | namespace TodoList.Application.Common; 6 | 7 | public abstract class SpecificationBase : ISpecification 8 | { 9 | protected SpecificationBase() { } 10 | protected SpecificationBase(Expression> criteria) => Criteria = criteria; 11 | 12 | public Expression> Criteria { get; private set; } 13 | public Func, IIncludableQueryable> Include { get; private set; } 14 | public List IncludeStrings { get; } = new(); 15 | public Expression> OrderBy { get; private set; } 16 | public Expression> OrderByDescending { get; private set; } 17 | 18 | public int Take { get; private set; } 19 | public int Skip { get; private set; } 20 | public bool IsPagingEnabled { get; private set; } 21 | 22 | public void AddCriteria(Expression> criteria) => Criteria = Criteria is not null ? Criteria.AndAlso(criteria) : criteria; 23 | 24 | protected virtual void AddInclude(Func, IIncludableQueryable> includeExpression) => Include = includeExpression; 25 | 26 | protected virtual void AddInclude(string includeString) => IncludeStrings.Add(includeString); 27 | 28 | protected virtual void ApplyPaging(int skip, int take) 29 | { 30 | Skip = skip; 31 | Take = take; 32 | IsPagingEnabled = true; 33 | } 34 | 35 | protected virtual void ApplyOrderBy(Expression> orderByExpression) => OrderBy = orderByExpression; 36 | protected virtual void ApplyOrderByDescending(Expression> orderByDescendingExpression) => OrderByDescending = orderByDescendingExpression; 37 | } 38 | 39 | // https://stackoverflow.com/questions/457316/combining-two-expressions-expressionfunct-bool 40 | public static class ExpressionExtensions 41 | { 42 | public static Expression> AndAlso(this Expression> expr1, Expression> expr2) 43 | { 44 | var parameter = Expression.Parameter(typeof(T)); 45 | 46 | var leftVisitor = new ReplaceExpressionVisitor(expr1.Parameters[0], parameter); 47 | var left = leftVisitor.Visit(expr1.Body); 48 | 49 | var rightVisitor = new ReplaceExpressionVisitor(expr2.Parameters[0], parameter); 50 | var right = rightVisitor.Visit(expr2.Body); 51 | 52 | return Expression.Lambda>( 53 | Expression.AndAlso(left ?? throw new InvalidOperationException(), 54 | right ?? throw new InvalidOperationException()), parameter); 55 | } 56 | 57 | private class ReplaceExpressionVisitor : ExpressionVisitor 58 | { 59 | private readonly Expression _oldValue; 60 | private readonly Expression _newValue; 61 | 62 | public ReplaceExpressionVisitor(Expression oldValue, Expression newValue) 63 | { 64 | _oldValue = oldValue; 65 | _newValue = newValue; 66 | } 67 | 68 | public override Expression Visit(Expression node) => node == _oldValue ? _newValue : base.Visit(node); 69 | } 70 | } -------------------------------------------------------------------------------- /src/TodoList.Application/Common/SpecificationEvaluator.cs: -------------------------------------------------------------------------------- 1 | using TodoList.Application.Common.Interfaces; 2 | 3 | namespace TodoList.Application.Common; 4 | 5 | public class SpecificationEvaluator where T : class 6 | { 7 | public static IQueryable GetQuery(IQueryable inputQuery, ISpecification? specification) 8 | { 9 | var query = inputQuery; 10 | 11 | if (specification?.Criteria is not null) 12 | { 13 | query = query.Where(specification.Criteria); 14 | } 15 | 16 | if (specification?.Include is not null) 17 | { 18 | query = specification.Include(query); 19 | } 20 | 21 | if (specification?.OrderBy is not null) 22 | { 23 | query = query.OrderBy(specification.OrderBy); 24 | } 25 | else if (specification?.OrderByDescending is not null) 26 | { 27 | query = query.OrderByDescending(specification.OrderByDescending); 28 | } 29 | 30 | if (specification?.IsPagingEnabled != false) 31 | { 32 | query = query.Skip(specification!.Skip).Take(specification.Take); 33 | } 34 | 35 | return query; 36 | } 37 | } -------------------------------------------------------------------------------- /src/TodoList.Application/DependencyInjection.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using FluentValidation; 3 | using MediatR; 4 | using Microsoft.Extensions.DependencyInjection; 5 | using TodoList.Application.Common; 6 | using TodoList.Application.Common.Behaviors; 7 | using TodoList.Application.Common.Interfaces; 8 | 9 | namespace TodoList.Application; 10 | 11 | public static class DependencyInjection 12 | { 13 | public static IServiceCollection AddApplication(this IServiceCollection services) 14 | { 15 | services.AddAutoMapper(Assembly.GetExecutingAssembly()); 16 | services.AddMediatR(Assembly.GetExecutingAssembly()); 17 | services.AddValidatorsFromAssembly(Assembly.GetExecutingAssembly()); 18 | services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidationBehaviour<,>)); 19 | services.AddScoped(typeof(IDataShaper<>), typeof(DataShaper<>)); 20 | 21 | services.AddHealthChecks().AddCheck("Random Health Check"); 22 | return services; 23 | } 24 | } -------------------------------------------------------------------------------- /src/TodoList.Application/TodoItems/Commands/CreateTodoItem/CreateTodoItemCommand.cs: -------------------------------------------------------------------------------- 1 | using MediatR; 2 | using TodoList.Application.Common.Interfaces; 3 | using TodoList.Domain.Entities; 4 | using TodoList.Domain.Events; 5 | 6 | namespace TodoList.Application.TodoItems.Commands.CreateTodoItem; 7 | 8 | public class CreateTodoItemCommand : IRequest 9 | { 10 | public Guid ListId { get; set; } 11 | 12 | public string? Title { get; set; } 13 | } 14 | 15 | public class CreateTodoItemCommandHandler : IRequestHandler 16 | { 17 | private readonly IRepository _repository; 18 | 19 | public CreateTodoItemCommandHandler(IRepository repository) 20 | { 21 | _repository = repository; 22 | } 23 | 24 | public async Task Handle(CreateTodoItemCommand request, CancellationToken cancellationToken) 25 | { 26 | var entity = new TodoItem 27 | { 28 | // 这个ListId在前文中的代码里漏掉了,需要添加到Domain.Entities.TodoItem实体上 29 | ListId = request.ListId, 30 | Title = request.Title, 31 | Done = false 32 | }; 33 | 34 | // 添加领域事件 35 | entity.DomainEvents.Add(new TodoItemCreatedEvent(entity)); 36 | 37 | await _repository.AddAsync(entity, cancellationToken); 38 | 39 | return entity; 40 | } 41 | } -------------------------------------------------------------------------------- /src/TodoList.Application/TodoItems/Commands/CreateTodoItem/CreateTodoItemValidator.cs: -------------------------------------------------------------------------------- 1 | using FluentValidation; 2 | using Microsoft.EntityFrameworkCore; 3 | using TodoList.Application.Common.Interfaces; 4 | using TodoList.Domain.Entities; 5 | 6 | namespace TodoList.Application.TodoItems.Commands.CreateTodoItem; 7 | 8 | public class CreateTodoItemCommandValidator : AbstractValidator 9 | { 10 | private readonly IRepository _repository; 11 | 12 | public CreateTodoItemCommandValidator(IRepository repository) 13 | { 14 | _repository = repository; 15 | 16 | // 我们把最大长度限制到10,以便更好地验证这个校验 17 | // 更多的用法请参考FluentValidation官方文档 18 | RuleFor(v => v.Title) 19 | .MaximumLength(10).WithMessage("TodoItem title must not exceed 10 characters.").WithSeverity(Severity.Warning) 20 | .NotEmpty().WithMessage("Title is required.").WithSeverity(Severity.Error) 21 | .MustAsync(BeUniqueTitle).WithMessage("The specified title already exists.").WithSeverity(Severity.Error); 22 | } 23 | 24 | public async Task BeUniqueTitle(string title, CancellationToken cancellationToken) 25 | { 26 | return await _repository.GetAsQueryable().AllAsync(l => l.Title != title, cancellationToken); 27 | } 28 | } -------------------------------------------------------------------------------- /src/TodoList.Application/TodoItems/Commands/PatchTodoItem/PatchTodoItemCommand.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using MediatR; 3 | using Microsoft.AspNetCore.JsonPatch; 4 | using TodoList.Application.Common.Exceptions; 5 | using TodoList.Application.Common.Interfaces; 6 | using TodoList.Application.TodoItems.Queries.GetTodoItems; 7 | using TodoList.Domain.Entities; 8 | 9 | namespace TodoList.Application.TodoItems.Commands.PatchTodoItem; 10 | 11 | public class PatchTodoItemCommand : IRequest 12 | { 13 | public Guid Id { get; set; } 14 | public JsonPatchDocument Todo { get; set; } 15 | } 16 | 17 | public class PatchTodoItemCommandHandler : IRequestHandler 18 | { 19 | private readonly IRepository _repository; 20 | private readonly IMapper _mapper; 21 | 22 | public PatchTodoItemCommandHandler(IRepository repository, IMapper mapper) 23 | { 24 | _repository = repository; 25 | _mapper = mapper; 26 | } 27 | 28 | public async Task Handle(PatchTodoItemCommand request, CancellationToken cancellationToken) 29 | { 30 | var entity = await _repository.GetAsync(request.Id); 31 | if (entity == null) 32 | { 33 | throw new NotFoundException(nameof(TodoItem), request.Id); 34 | } 35 | 36 | // 应用Patch 37 | var todoItemToPatch = _mapper.Map(entity); 38 | request.Todo.ApplyTo(todoItemToPatch); 39 | _mapper.Map(todoItemToPatch, entity); 40 | 41 | await _repository.SaveChangesAsync(cancellationToken); 42 | 43 | return entity; 44 | } 45 | } -------------------------------------------------------------------------------- /src/TodoList.Application/TodoItems/Commands/PatchTodoItem/TestPatchTodo.cs: -------------------------------------------------------------------------------- 1 | namespace TodoList.Application.TodoItems.Commands.PatchTodoItem; 2 | 3 | public class TestPatchTodo 4 | { 5 | public Guid Id { get; set; } 6 | public string Title { get; set; } 7 | } -------------------------------------------------------------------------------- /src/TodoList.Application/TodoItems/Commands/PatchTodoItem/TodoItemPatchDto.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using TodoList.Application.Common.Mappings; 3 | using TodoList.Application.TodoItems.Queries.GetTodoItems; 4 | using TodoList.Domain.Entities; 5 | 6 | namespace TodoList.Application.TodoItems.Commands.PatchTodoItem; 7 | 8 | // 实现IMapFrom接口 9 | public class TodoItemPatchDto 10 | { 11 | public Guid Id { get; set; } 12 | public Guid ListId { get; set; } 13 | public string? Title { get; set; } 14 | public bool Done { get; set; } 15 | } -------------------------------------------------------------------------------- /src/TodoList.Application/TodoItems/Commands/UpdateTodoItem/UpdateTodoItemCommand.cs: -------------------------------------------------------------------------------- 1 | using MediatR; 2 | using TodoList.Application.Common.Exceptions; 3 | using TodoList.Application.Common.Interfaces; 4 | using TodoList.Domain.Entities; 5 | 6 | namespace TodoList.Application.TodoItems.Commands.UpdateTodoItem; 7 | 8 | public class UpdateTodoItemCommand : IRequest 9 | { 10 | public Guid Id { get; set; } 11 | public string? Title { get; set; } 12 | public bool Done { get; set; } 13 | } 14 | 15 | public class UpdateTodoItemCommandHandler : IRequestHandler 16 | { 17 | private readonly IRepository _repository; 18 | 19 | public UpdateTodoItemCommandHandler(IRepository repository) 20 | { 21 | _repository = repository; 22 | } 23 | 24 | public async Task Handle(UpdateTodoItemCommand request, CancellationToken cancellationToken) 25 | { 26 | var entity = await _repository.GetAsync(request.Id); 27 | if (entity == null) 28 | { 29 | throw new NotFoundException(nameof(TodoItem), request.Id); 30 | } 31 | 32 | entity.Title = request.Title ?? entity.Title; 33 | entity.Done = request.Done; 34 | 35 | await _repository.UpdateAsync(entity, cancellationToken); 36 | 37 | return entity; 38 | } 39 | } -------------------------------------------------------------------------------- /src/TodoList.Application/TodoItems/EventHandlers/TodoItemCompleteEventHandler.cs: -------------------------------------------------------------------------------- 1 | using MediatR; 2 | using Microsoft.Extensions.Logging; 3 | using TodoList.Application.Common.Models; 4 | using TodoList.Domain.Events; 5 | 6 | namespace TodoList.Application.TodoItems.EventHandlers; 7 | 8 | public class TodoItemCompletedEventHandler : INotificationHandler> 9 | { 10 | private readonly ILogger _logger; 11 | 12 | public TodoItemCompletedEventHandler(ILogger logger) 13 | { 14 | _logger = logger; 15 | } 16 | 17 | public Task Handle(DomainEventNotification notification, CancellationToken cancellationToken) 18 | { 19 | var domainEvent = notification.DomainEvent; 20 | 21 | // 这里我们还是只做日志输出,实际使用中根据需要进行业务逻辑处理,但是在Handler中不建议继续Send其他Command或Notification 22 | _logger.LogInformation("TodoList Domain Event: {DomainEvent}", domainEvent.GetType().Name); 23 | 24 | return Task.CompletedTask; 25 | } 26 | } -------------------------------------------------------------------------------- /src/TodoList.Application/TodoItems/Queries/GetTodoItems/GetTodoItemValidator.cs: -------------------------------------------------------------------------------- 1 | using FluentValidation; 2 | 3 | namespace TodoList.Application.TodoItems.Queries.GetTodoItems; 4 | 5 | public class GetTodoItemValidator : AbstractValidator 6 | { 7 | public GetTodoItemValidator() 8 | { 9 | RuleFor(x => x.ListId).NotEmpty().WithMessage("ListId is required."); 10 | RuleFor(x => x.PageNumber).GreaterThanOrEqualTo(1).WithMessage("PageNumber at least greater than or equal to 1."); 11 | RuleFor(x => x.PageSize).GreaterThanOrEqualTo(1).WithMessage("PageSize at least greater than or equal to 1."); 12 | } 13 | } -------------------------------------------------------------------------------- /src/TodoList.Application/TodoItems/Queries/GetTodoItems/GetTodoItemsWithConditionQuery.cs: -------------------------------------------------------------------------------- 1 | using System.Dynamic; 2 | using AutoMapper; 3 | using AutoMapper.QueryableExtensions; 4 | using MediatR; 5 | using TodoList.Application.Common.Extensions; 6 | using TodoList.Application.Common.Interfaces; 7 | using TodoList.Application.Common.Mappings; 8 | using TodoList.Application.Common.Models; 9 | using TodoList.Application.TodoItems.Specs; 10 | using TodoList.Domain.Entities; 11 | using TodoList.Domain.Enums; 12 | 13 | namespace TodoList.Application.TodoItems.Queries.GetTodoItems; 14 | 15 | public class GetTodoItemsWithConditionQuery : IRequest> 16 | { 17 | public Guid ListId { get; set; } 18 | public bool? Done { get; set; } 19 | public string? Title { get; set; } 20 | // 前端指明需要返回的字段 21 | public string? Fields { get; set; } 22 | public PriorityLevel? PriorityLevel { get; set; } 23 | public string? SortOrder { get; set; } = "title_asc"; 24 | public int PageNumber { get; set; } = 1; 25 | public int PageSize { get; set; } = 10; 26 | } 27 | 28 | public class GetTodoItemsWithConditionQueryHandler : IRequestHandler> 29 | { 30 | private readonly IRepository _repository; 31 | private readonly IMapper _mapper; 32 | private readonly IDataShaper _shaper; 33 | 34 | public GetTodoItemsWithConditionQueryHandler(IRepository repository, IMapper mapper, IDataShaper shaper) 35 | { 36 | _repository = repository; 37 | _mapper = mapper; 38 | _shaper = shaper; 39 | } 40 | 41 | public Task> Handle(GetTodoItemsWithConditionQuery request, CancellationToken cancellationToken) 42 | { 43 | var spec = new TodoItemSpec(request); 44 | return Task.FromResult( 45 | _repository 46 | .GetAsQueryable(spec) 47 | .ProjectTo(_mapper.ConfigurationProvider) 48 | .AsEnumerable() 49 | // 进行数据塑形和分页返回 50 | .ShapeData(_shaper, request.Fields) 51 | .PaginatedListFromEnumerable(request.PageNumber, request.PageSize) 52 | ); 53 | } 54 | } -------------------------------------------------------------------------------- /src/TodoList.Application/TodoItems/Queries/GetTodoItems/GetTodoItemsWithPaginationQuery.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using AutoMapper; 3 | using AutoMapper.QueryableExtensions; 4 | using MediatR; 5 | using TodoList.Application.Common.Interfaces; 6 | using TodoList.Application.Common.Mappings; 7 | using TodoList.Application.Common.Models; 8 | using TodoList.Application.TodoItems.Specs; 9 | using TodoList.Domain.Entities; 10 | 11 | namespace TodoList.Application.TodoItems.Queries.GetTodoItems; 12 | 13 | public class GetTodoItemsWithPaginationQuery : IRequest> 14 | { 15 | public Guid ListId { get; set; } 16 | public int PageNumber { get; set; } = 1; 17 | public int PageSize { get; set; } = 10; 18 | } 19 | 20 | public class GetTodoItemsWithPaginationQueryHandler : IRequestHandler> 21 | { 22 | private readonly IRepository _repository; 23 | private readonly IMapper _mapper; 24 | 25 | public GetTodoItemsWithPaginationQueryHandler(IRepository repository, IMapper mapper) 26 | { 27 | _repository = repository; 28 | _mapper = mapper; 29 | } 30 | 31 | public async Task> Handle(GetTodoItemsWithPaginationQuery request, CancellationToken cancellationToken) 32 | { 33 | return await _repository 34 | .GetAsQueryable(x => x.ListId == request.ListId) 35 | .OrderBy(x => x.Title) 36 | .ProjectTo(_mapper.ConfigurationProvider) 37 | .PaginatedListAsync(request.PageNumber, request.PageSize); 38 | } 39 | } -------------------------------------------------------------------------------- /src/TodoList.Application/TodoItems/Queries/GetTodoItems/TodoItemDto.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using TodoList.Application.Common.Mappings; 3 | using TodoList.Domain.Entities; 4 | 5 | namespace TodoList.Application.TodoItems.Queries.GetTodoItems; 6 | 7 | // 实现IMapFrom接口 8 | public class TodoItemDto : IMapFrom 9 | { 10 | public Guid Id { get; set; } 11 | 12 | public Guid ListId { get; set; } 13 | 14 | public string? Title { get; set; } 15 | 16 | public bool Done { get; set; } 17 | 18 | public int Priority { get; set; } 19 | 20 | // 实现接口定义的Mapping方法,并提供除了Convention之外的特殊字段的转换规则 21 | public void Mapping(Profile profile) 22 | { 23 | profile.CreateMap() 24 | .ForMember(d => d.Priority, opt => opt.MapFrom(s => (int)s.Priority)); 25 | 26 | profile.CreateMap() 27 | .ForMember(d => d.Priority, opt => opt.MapFrom(s => (int)s.Priority)) 28 | .ReverseMap(); 29 | } 30 | } -------------------------------------------------------------------------------- /src/TodoList.Application/TodoItems/Specs/TodoItemSpec.cs: -------------------------------------------------------------------------------- 1 | using TodoList.Application.Common; 2 | using TodoList.Application.TodoItems.Queries.GetTodoItems; 3 | using TodoList.Domain.Entities; 4 | using TodoList.Domain.Enums; 5 | 6 | namespace TodoList.Application.TodoItems.Specs; 7 | 8 | public sealed class TodoItemSpec : SpecificationBase 9 | { 10 | public TodoItemSpec(bool done, PriorityLevel priority) : base(t => t.Done == done && t.Priority == priority) 11 | { 12 | } 13 | 14 | public TodoItemSpec(Guid id) : base(t => t.Id == id) 15 | { 16 | } 17 | 18 | public TodoItemSpec(GetTodoItemsWithConditionQuery query) : 19 | base(x => x.ListId == query.ListId 20 | && (!query.Done.HasValue || x.Done == query.Done) 21 | && (!query.PriorityLevel.HasValue || x.Priority == query.PriorityLevel) 22 | && (string.IsNullOrEmpty(query.Title) || x.Title!.Trim().ToLower().Contains(query.Title!.ToLower()))) 23 | { 24 | if (string.IsNullOrEmpty(query.SortOrder)) 25 | return; 26 | 27 | switch (query.SortOrder) 28 | { 29 | // 仅作有限的演示 30 | default: 31 | ApplyOrderBy(x => x.Title!); 32 | break; 33 | case "title_desc": 34 | ApplyOrderByDescending(x =>x .Title!); 35 | break; 36 | case "priority_asc": 37 | ApplyOrderBy(x => x.Priority); 38 | break; 39 | case "priority_desc": 40 | ApplyOrderByDescending(x => x.Priority); 41 | break; 42 | } 43 | } 44 | } -------------------------------------------------------------------------------- /src/TodoList.Application/TodoList.Application.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | net6.0 22 | enable 23 | enable 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /src/TodoList.Application/TodoLists/Commands/CreateTodoList/CreateTodoListCommand.cs: -------------------------------------------------------------------------------- 1 | using MediatR; 2 | using TodoList.Application.Common.Interfaces; 3 | using TodoList.Domain.ValueObjects; 4 | 5 | namespace TodoList.Application.TodoLists.Commands.CreateTodoList; 6 | 7 | /// 8 | /// 创建TodoList指令对象 9 | /// 10 | public class CreateTodoListCommand : IRequest 11 | { 12 | /// 13 | /// TodoList的名称 14 | /// 15 | public string? Title { get; set; } 16 | 17 | /// 18 | /// TodoList使用的主题颜色 19 | /// 20 | public string? Colour { get; set; } 21 | } 22 | 23 | public class CreateTodoListCommandHandler : IRequestHandler 24 | { 25 | private readonly IRepository _repository; 26 | 27 | public CreateTodoListCommandHandler(IRepository repository) 28 | { 29 | _repository = repository; 30 | } 31 | 32 | public async Task Handle(CreateTodoListCommand request, CancellationToken cancellationToken) 33 | { 34 | var entity = new Domain.Entities.TodoList 35 | { 36 | Title = request.Title, 37 | Colour = Colour.From(request.Colour ?? string.Empty) 38 | }; 39 | 40 | await _repository.AddAsync(entity, cancellationToken); 41 | return entity; 42 | } 43 | } -------------------------------------------------------------------------------- /src/TodoList.Application/TodoLists/Commands/DeleteTodoList/DeleteTodoListCommand.cs: -------------------------------------------------------------------------------- 1 | using MediatR; 2 | using TodoList.Application.Common.Exceptions; 3 | using TodoList.Application.Common.Interfaces; 4 | 5 | namespace TodoList.Application.TodoLists.Commands.DeleteTodoList; 6 | 7 | public class DeleteTodoListCommand : IRequest 8 | { 9 | public Guid Id { get; set; } 10 | } 11 | 12 | public class DeleteTodoListCommandHandler : IRequestHandler 13 | { 14 | private readonly IRepository _repository; 15 | 16 | public DeleteTodoListCommandHandler(IRepository repository) 17 | { 18 | _repository = repository; 19 | } 20 | 21 | public async Task Handle(DeleteTodoListCommand request, CancellationToken cancellationToken) 22 | { 23 | var entity = await _repository.GetAsync(request.Id); 24 | if (entity == null) 25 | { 26 | throw new NotFoundException(nameof(TodoList), request.Id); 27 | } 28 | 29 | await _repository.DeleteAsync(entity,cancellationToken); 30 | 31 | // 对于Delete操作,演示中并不返回任何实际的对象,可以结合实际需要返回特定的对象。Unit对象在MediatR中表示Void 32 | return Unit.Value; 33 | } 34 | } -------------------------------------------------------------------------------- /src/TodoList.Application/TodoLists/Queries/GetSingleTodo/GetSingleTodoQuery.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using AutoMapper.QueryableExtensions; 3 | using MediatR; 4 | using Microsoft.EntityFrameworkCore; 5 | using TodoList.Application.Common.Interfaces; 6 | using TodoList.Application.TodoLists.Specs; 7 | 8 | namespace TodoList.Application.TodoLists.Queries.GetSingleTodo; 9 | 10 | public class GetSingleTodoQuery : IRequest 11 | { 12 | public Guid ListId { get; set; } 13 | } 14 | 15 | public class ExportTodosQueryHandler : IRequestHandler 16 | { 17 | private readonly IRepository _repository; 18 | private readonly IMapper _mapper; 19 | 20 | public ExportTodosQueryHandler(IRepository repository, IMapper mapper) 21 | { 22 | _repository = repository; 23 | _mapper = mapper; 24 | } 25 | 26 | public async Task Handle(GetSingleTodoQuery request, CancellationToken cancellationToken) 27 | { 28 | var spec = new TodoListSpec(request.ListId, true); 29 | return await _repository 30 | .GetAsQueryable(spec) 31 | .AsNoTracking() 32 | .ProjectTo(_mapper.ConfigurationProvider) 33 | .FirstOrDefaultAsync(cancellationToken); 34 | } 35 | } -------------------------------------------------------------------------------- /src/TodoList.Application/TodoLists/Queries/GetSingleTodo/TodoListDto.cs: -------------------------------------------------------------------------------- 1 | using TodoList.Application.Common.Mappings; 2 | using TodoList.Application.TodoItems.Queries.GetTodoItems; 3 | 4 | namespace TodoList.Application.TodoLists.Queries.GetSingleTodo; 5 | 6 | // 实现IMapFrom接口,因为此Dto不涉及特殊字段的Mapping规则 7 | // 并且属性名称与领域实体保持一致,根据Convention规则默认可以完成Mapping,不需要额外实现 8 | public class TodoListDto : IMapFrom 9 | { 10 | public Guid Id { get; set; } 11 | public string? Title { get; set; } 12 | public string? Colour { get; set; } 13 | 14 | public IList Items { get; set; } = new List(); 15 | } 16 | -------------------------------------------------------------------------------- /src/TodoList.Application/TodoLists/Queries/GetTodos/GetTodosQuery.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using AutoMapper.QueryableExtensions; 3 | using MediatR; 4 | using Microsoft.EntityFrameworkCore; 5 | using TodoList.Application.Common.Interfaces; 6 | 7 | namespace TodoList.Application.TodoLists.Queries.GetTodos; 8 | 9 | public class GetTodosQuery : IRequest> 10 | { 11 | } 12 | 13 | public class GetTodosQueryHandler : IRequestHandler> 14 | { 15 | private readonly IRepository _repository; 16 | private readonly IMapper _mapper; 17 | 18 | public GetTodosQueryHandler(IRepository repository, IMapper mapper) 19 | { 20 | _repository = repository; 21 | _mapper = mapper; 22 | } 23 | 24 | public async Task> Handle(GetTodosQuery request, CancellationToken cancellationToken) 25 | { 26 | return await _repository 27 | .GetAsQueryable() 28 | .AsNoTracking() 29 | .ProjectTo(_mapper.ConfigurationProvider) 30 | .OrderBy(t => t.Title) 31 | .ToListAsync(cancellationToken); 32 | } 33 | } -------------------------------------------------------------------------------- /src/TodoList.Application/TodoLists/Queries/GetTodos/TodoListBriefDto.cs: -------------------------------------------------------------------------------- 1 | using TodoList.Application.Common.Mappings; 2 | 3 | namespace TodoList.Application.TodoLists.Queries.GetTodos; 4 | 5 | // 实现IMapFrom接口,因为此Dto不涉及特殊字段的Mapping规则 6 | // 并且属性名称与领域实体保持一致,根据Convention规则默认可以完成Mapping,不需要额外实现 7 | public class TodoListBriefDto : IMapFrom 8 | { 9 | public Guid Id { get; set; } 10 | public string? Title { get; set; } 11 | public string? Colour { get; set; } 12 | } -------------------------------------------------------------------------------- /src/TodoList.Application/TodoLists/Specs/TodoListSpec.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using TodoList.Application.Common; 3 | 4 | namespace TodoList.Application.TodoLists.Specs; 5 | 6 | public sealed class TodoListSpec : SpecificationBase 7 | { 8 | public TodoListSpec(Guid id, bool includeItems = false) : base(t => t.Id == id) 9 | { 10 | if (includeItems) 11 | { 12 | AddInclude(t => t.Include(i => i.Items)); 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/TodoList.Domain/Base/AuditableEntity.cs: -------------------------------------------------------------------------------- 1 | namespace TodoList.Domain.Base; 2 | public abstract class AuditableEntity 3 | { 4 | public DateTime Created { get; set; } 5 | public string? CreatedBy { get; set; } 6 | public DateTime? LastModified { get; set; } 7 | public string? LastModifiedBy { get; set; } 8 | } -------------------------------------------------------------------------------- /src/TodoList.Domain/Base/DomainEvent.cs: -------------------------------------------------------------------------------- 1 | namespace TodoList.Domain.Base; 2 | 3 | public abstract class DomainEvent 4 | { 5 | protected DomainEvent() 6 | { 7 | DateOccurred = DateTimeOffset.UtcNow; 8 | } 9 | public bool IsPublished { get; set; } 10 | public DateTimeOffset DateOccurred { get; protected set; } = DateTime.UtcNow; 11 | } -------------------------------------------------------------------------------- /src/TodoList.Domain/Base/Interfaces/IAggregateRoot.cs: -------------------------------------------------------------------------------- 1 | namespace TodoList.Domain.Base.Interfaces; 2 | public interface IAggregateRoot { } -------------------------------------------------------------------------------- /src/TodoList.Domain/Base/Interfaces/IEntity.cs: -------------------------------------------------------------------------------- 1 | namespace TodoList.Domain.Base.Interfaces; 2 | 3 | public interface IEntity 4 | { 5 | public T Id { get; set; } 6 | } -------------------------------------------------------------------------------- /src/TodoList.Domain/Base/Interfaces/IHasDomainEvent.cs: -------------------------------------------------------------------------------- 1 | namespace TodoList.Domain.Base.Interfaces; 2 | public interface IHasDomainEvent 3 | { 4 | public List DomainEvents { get; set; } 5 | } 6 | -------------------------------------------------------------------------------- /src/TodoList.Domain/Base/ValueObject.cs: -------------------------------------------------------------------------------- 1 | namespace TodoList.Domain.Base; 2 | 3 | public abstract class ValueObject 4 | { 5 | protected static bool EqualOperator(ValueObject left, ValueObject right) 6 | { 7 | if (left is null ^ right is null) 8 | { 9 | return false; 10 | } 11 | 12 | return left?.Equals(right!) != false; 13 | } 14 | 15 | protected static bool NotEqualOperator(ValueObject left, ValueObject right) 16 | { 17 | return !(EqualOperator(left, right)); 18 | } 19 | 20 | protected abstract IEnumerable GetEqualityComponents(); 21 | 22 | public override bool Equals(object? obj) 23 | { 24 | if (obj == null || obj.GetType() != GetType()) 25 | { 26 | return false; 27 | } 28 | 29 | var other = (ValueObject)obj; 30 | return GetEqualityComponents().SequenceEqual(other.GetEqualityComponents()); 31 | } 32 | 33 | public override int GetHashCode() 34 | { 35 | return GetEqualityComponents() 36 | .Select(x => x != null ? x.GetHashCode() : 0) 37 | .Aggregate((x, y) => x ^ y); 38 | } 39 | } -------------------------------------------------------------------------------- /src/TodoList.Domain/Entities/TodoItem.cs: -------------------------------------------------------------------------------- 1 | using TodoList.Domain.Base; 2 | using TodoList.Domain.Base.Interfaces; 3 | using TodoList.Domain.Enums; 4 | using TodoList.Domain.Events; 5 | 6 | namespace TodoList.Domain.Entities; 7 | 8 | public class TodoItem : AuditableEntity, IEntity, IHasDomainEvent 9 | { 10 | public Guid Id { get; set; } 11 | public string? Title { get; set; } 12 | public PriorityLevel Priority { get; set; } 13 | 14 | private bool _done; 15 | public bool Done 16 | { 17 | get => _done; 18 | set 19 | { 20 | if (value && _done == false) 21 | { 22 | DomainEvents.Add(new TodoItemCompletedEvent(this)); 23 | } 24 | 25 | _done = value; 26 | } 27 | } 28 | 29 | public Guid ListId { get; set; } 30 | public TodoList List { get; set; } = null!; 31 | 32 | public List DomainEvents { get; set; } = new List(); 33 | } 34 | -------------------------------------------------------------------------------- /src/TodoList.Domain/Entities/TodoList.cs: -------------------------------------------------------------------------------- 1 | using TodoList.Domain.Base; 2 | using TodoList.Domain.Base.Interfaces; 3 | using TodoList.Domain.ValueObjects; 4 | 5 | namespace TodoList.Domain.Entities; 6 | 7 | public class TodoList : AuditableEntity, IEntity, IHasDomainEvent, IAggregateRoot 8 | { 9 | public Guid Id { get; set; } 10 | public string? Title { get; set; } 11 | public Colour Colour { get; set; } = Colour.White; 12 | 13 | public IList Items { get; private set; } = new List(); 14 | public List DomainEvents { get; set; } = new List(); 15 | } 16 | -------------------------------------------------------------------------------- /src/TodoList.Domain/Enums/PriorityLevel.cs: -------------------------------------------------------------------------------- 1 | namespace TodoList.Domain.Enums; 2 | public enum PriorityLevel 3 | { 4 | None = 0, 5 | Low = 1, 6 | Medium = 2, 7 | High = 3 8 | } -------------------------------------------------------------------------------- /src/TodoList.Domain/Events/TodoItemCompletedEvent.cs: -------------------------------------------------------------------------------- 1 | using TodoList.Domain.Base; 2 | using TodoList.Domain.Entities; 3 | 4 | namespace TodoList.Domain.Events; 5 | 6 | public class TodoItemCompletedEvent : DomainEvent 7 | { 8 | public TodoItemCompletedEvent(TodoItem item) => Item = item; 9 | 10 | public TodoItem Item { get; } 11 | } 12 | -------------------------------------------------------------------------------- /src/TodoList.Domain/Events/TodoItemCreatedEvent.cs: -------------------------------------------------------------------------------- 1 | using TodoList.Domain.Base; 2 | using TodoList.Domain.Entities; 3 | 4 | namespace TodoList.Domain.Events; 5 | 6 | public class TodoItemCreatedEvent : DomainEvent 7 | { 8 | public TodoItemCreatedEvent(TodoItem item) 9 | => Item = item; 10 | public TodoItem Item { get; } 11 | } -------------------------------------------------------------------------------- /src/TodoList.Domain/Exceptions/UnsupportedColourException.cs: -------------------------------------------------------------------------------- 1 | namespace TodoList.Domain.Exceptions; 2 | 3 | public class UnsupportedColourException : Exception 4 | { 5 | public UnsupportedColourException(string code) 6 | : base($"Colour \"{code}\" is unsupported.") 7 | { 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/TodoList.Domain/TodoList.Domain.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /src/TodoList.Domain/ValueObjects/Colour.cs: -------------------------------------------------------------------------------- 1 | using TodoList.Domain.Base; 2 | using TodoList.Domain.Exceptions; 3 | 4 | namespace TodoList.Domain.ValueObjects; 5 | 6 | public class Colour : ValueObject 7 | { 8 | static Colour() { } 9 | private Colour() { } 10 | private Colour(string code) => Code = code; 11 | 12 | public static Colour From(string code) 13 | { 14 | var colour = new Colour { Code = code }; 15 | 16 | if (!SupportedColours.Contains(colour)) 17 | { 18 | throw new UnsupportedColourException(code); 19 | } 20 | 21 | return colour; 22 | } 23 | 24 | public static Colour White => new("#FFFFFF"); 25 | public static Colour Red => new("#FF5733"); 26 | public static Colour Orange => new("#FFC300"); 27 | public static Colour Yellow => new("#FFFF66"); 28 | public static Colour Green => new("#CCFF99 "); 29 | public static Colour Blue => new("#6666FF"); 30 | public static Colour Purple => new("#9966CC"); 31 | public static Colour Grey => new("#999999"); 32 | 33 | public string Code { get; private set; } = "#000000"; 34 | 35 | public static implicit operator string(Colour colour) => colour.ToString(); 36 | public static explicit operator Colour(string code) => From(code); 37 | 38 | public override string ToString() => Code; 39 | 40 | protected static IEnumerable SupportedColours 41 | { 42 | get 43 | { 44 | yield return White; 45 | yield return Red; 46 | yield return Orange; 47 | yield return Yellow; 48 | yield return Green; 49 | yield return Blue; 50 | yield return Purple; 51 | yield return Grey; 52 | } 53 | } 54 | 55 | protected override IEnumerable GetEqualityComponents() 56 | { 57 | yield return Code; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/TodoList.Infrastructure/ApplicationStartupExtensions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Builder; 2 | using Microsoft.AspNetCore.Identity; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.Extensions.DependencyInjection; 5 | using TodoList.Infrastructure.Identity; 6 | using TodoList.Infrastructure.Persistence; 7 | 8 | namespace TodoList.Infrastructure; 9 | 10 | public static class ApplicationStartupExtensions 11 | { 12 | public static async Task MigrateDatabase(this WebApplication app) 13 | { 14 | using var scope = app.Services.CreateScope(); 15 | var services = scope.ServiceProvider; 16 | 17 | try 18 | { 19 | var context = services.GetRequiredService(); 20 | await context.Database.MigrateAsync(); 21 | 22 | var userManager = services.GetRequiredService>(); 23 | var roleManager = services.GetRequiredService>(); 24 | 25 | await TodoListDbContextSeed.SeedDefaultUserAsync(userManager, roleManager); 26 | 27 | // 生成种子数据 28 | await TodoListDbContextSeed.SeedSampleDataAsync(context); 29 | 30 | // 更新部分种子数据以便查看审计字段 31 | await TodoListDbContextSeed.UpdateSampleDataAsync(context); 32 | } 33 | catch (Exception ex) 34 | { 35 | throw new Exception($"An error occurred migrating the DB: {ex.Message}"); 36 | } 37 | } 38 | } -------------------------------------------------------------------------------- /src/TodoList.Infrastructure/DependencyInjection.cs: -------------------------------------------------------------------------------- 1 | using System.Text; 2 | using Microsoft.AspNetCore.Authentication.JwtBearer; 3 | using Microsoft.AspNetCore.Identity; 4 | using Microsoft.EntityFrameworkCore; 5 | using Microsoft.Extensions.Configuration; 6 | using Microsoft.Extensions.DependencyInjection; 7 | using Microsoft.IdentityModel.Tokens; 8 | using TodoList.Application.Common.Configurations; 9 | using TodoList.Application.Common.Interfaces; 10 | using TodoList.Infrastructure.Identity; 11 | using TodoList.Infrastructure.Persistence; 12 | using TodoList.Infrastructure.Persistence.Repositories; 13 | using TodoList.Infrastructure.Services; 14 | 15 | namespace TodoList.Infrastructure; 16 | 17 | public static class DependencyInjection 18 | { 19 | public static IServiceCollection AddInfrastructure(this IServiceCollection services, IConfiguration configuration) 20 | { 21 | services.AddDbContext(options => 22 | options.UseSqlServer( 23 | configuration.GetConnectionString("SqlServerConnection"), 24 | b => b.MigrationsAssembly(typeof(TodoListDbContext).Assembly.FullName))); 25 | 26 | services.AddScoped(typeof(IRepository<>), typeof(RepositoryBase<>)); 27 | 28 | // 配置内建的IdentityServer用于API授权 29 | // services 30 | // .AddIdentityServer() 31 | // .AddDeveloperSigningCredential() 32 | // .AddApiAuthorization(); 33 | 34 | // 配置认证服务 35 | services 36 | .AddIdentity(o => 37 | { 38 | o.Password.RequireDigit = true; 39 | o.Password.RequiredLength = 6; 40 | o.Password.RequireLowercase = true; 41 | o.Password.RequireUppercase = false; 42 | o.Password.RequireNonAlphanumeric = false; 43 | o.User.RequireUniqueEmail = true; 44 | }) 45 | .AddEntityFrameworkStores() 46 | .AddDefaultTokenProviders(); 47 | 48 | // 注入认证服务 49 | services.AddTransient(); 50 | 51 | // 增加依赖注入 52 | services.AddScoped(); 53 | 54 | // 添加认证方法为JWT Token认证 55 | var jwtConfiguration = new JwtConfiguration(); 56 | configuration.Bind(jwtConfiguration.Section, jwtConfiguration); 57 | 58 | // 使用IOptions配置 59 | services.Configure("JwtSettings", configuration.GetSection("JwtSettings")); 60 | services.Configure("JwtApiV2Settings", configuration.GetSection("JwtApiV2Settings")); 61 | 62 | services 63 | .AddAuthentication(opt => 64 | { 65 | opt.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; 66 | opt.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; 67 | }) 68 | .AddJwtBearer(options => 69 | { 70 | options.TokenValidationParameters = new TokenValidationParameters 71 | { 72 | ValidateIssuer = true, 73 | ValidateAudience = true, 74 | ValidateLifetime = true, 75 | ValidateIssuerSigningKey = true, 76 | 77 | // 改为使用配置类成员获取 78 | ValidIssuer = jwtConfiguration.ValidIssuer, 79 | ValidAudience = jwtConfiguration.ValidAudience, 80 | IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Environment.GetEnvironmentVariable("SECRET") ?? "TodoListApiSecretKey")) 81 | }; 82 | }); 83 | 84 | // 添加授权Policy是基于角色的,策略名称为OnlyAdmin,策略要求具有Administrator角色 85 | services.AddAuthorization(options => 86 | { 87 | options.AddPolicy("OnlyAdmin", policy => policy.RequireRole("Administrator")); 88 | options.AddPolicy("OnlySuper", policy => policy.RequireRole("SuperAdmin")); 89 | }); 90 | 91 | return services; 92 | } 93 | } -------------------------------------------------------------------------------- /src/TodoList.Infrastructure/Identity/ApplicationUser.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Identity; 2 | 3 | namespace TodoList.Infrastructure.Identity; 4 | 5 | public class ApplicationUser : IdentityUser 6 | { 7 | public string? RefreshToken { get; set; } 8 | public DateTime RefreshTokenExpiryTime { get; set; } 9 | } -------------------------------------------------------------------------------- /src/TodoList.Infrastructure/Identity/IdentityService.cs: -------------------------------------------------------------------------------- 1 | using System.IdentityModel.Tokens.Jwt; 2 | using System.Security.Claims; 3 | using System.Security.Cryptography; 4 | using System.Text; 5 | using Microsoft.AspNetCore.Http; 6 | using Microsoft.AspNetCore.Identity; 7 | using Microsoft.Extensions.Logging; 8 | using Microsoft.Extensions.Options; 9 | using Microsoft.IdentityModel.Tokens; 10 | using TodoList.Application.Common.Configurations; 11 | using TodoList.Application.Common.Interfaces; 12 | using TodoList.Application.Common.Models; 13 | 14 | namespace TodoList.Infrastructure.Identity; 15 | 16 | public class IdentityService : IIdentityService 17 | { 18 | private readonly ILogger _logger; 19 | 20 | private readonly UserManager _userManager; 21 | 22 | private readonly JwtConfiguration _jwtConfiguration; 23 | 24 | private ApplicationUser? User; 25 | 26 | public IdentityService( 27 | ILogger logger, 28 | UserManager userManager, 29 | IOptionsMonitor jwtOptions) 30 | { 31 | _logger = logger; 32 | _userManager = userManager; 33 | 34 | // 使用IOptionsMonitor加载配置 35 | _jwtConfiguration = jwtOptions.Get("JwtSettings"); 36 | } 37 | 38 | public async Task CreateUserAsync(string userName, string password) 39 | { 40 | var user = new ApplicationUser 41 | { 42 | UserName = userName, 43 | Email = userName 44 | }; 45 | 46 | await _userManager.CreateAsync(user, password); 47 | 48 | return user.Id; 49 | } 50 | 51 | public async Task ValidateUserAsync(UserForAuthentication userForAuthentication) 52 | { 53 | User = await _userManager.FindByNameAsync(userForAuthentication.UserName); 54 | 55 | var result = User != null && await _userManager.CheckPasswordAsync(User, userForAuthentication.Password); 56 | if (!result) 57 | { 58 | _logger.LogWarning($"{nameof(ValidateUserAsync)}: Authentication failed. Wrong username or password."); 59 | } 60 | 61 | return result; 62 | } 63 | 64 | public async Task CreateTokenAsync(bool populateExpiry) 65 | { 66 | var signingCredentials = GetSigningCredentials(); 67 | var claims = await GetClaims(); 68 | var tokenOptions = GenerateTokenOptions(signingCredentials, claims); 69 | 70 | var refreshToken = GenerateRefreshToken(); 71 | 72 | User!.RefreshToken = refreshToken; 73 | if(populateExpiry) 74 | User!.RefreshTokenExpiryTime = DateTime.Now.AddDays(7); 75 | 76 | await _userManager.UpdateAsync(User); 77 | 78 | var accessToken = new JwtSecurityTokenHandler().WriteToken(tokenOptions); 79 | 80 | return new ApplicationToken(accessToken, refreshToken); 81 | } 82 | 83 | public async Task RefreshTokenAsync(ApplicationToken token) 84 | { 85 | var principal = GetPrincipalFromExpiredToken(token.AccessToken); 86 | 87 | var user = await _userManager.FindByNameAsync(principal.Identity?.Name); 88 | if (user == null || user.RefreshToken != token.RefreshToken || user.RefreshTokenExpiryTime <= DateTime.Now) 89 | { 90 | throw new BadHttpRequestException("provided token has some invalid value"); 91 | } 92 | 93 | User = user; 94 | return await CreateTokenAsync(true); 95 | } 96 | 97 | private ClaimsPrincipal GetPrincipalFromExpiredToken(string token) 98 | { 99 | var tokenValidationParameters = new TokenValidationParameters { 100 | ValidateAudience = true, 101 | ValidateIssuer = true, 102 | ValidateIssuerSigningKey = true, 103 | IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Environment.GetEnvironmentVariable("SECRET") ?? "TodoListApiSecretKey")), ValidateLifetime = true, 104 | // 更改为通过类对象获取 105 | ValidIssuer = _jwtConfiguration.ValidIssuer, 106 | ValidAudience = _jwtConfiguration.ValidAudience 107 | }; 108 | 109 | var tokenHandler = new JwtSecurityTokenHandler(); 110 | var principal = tokenHandler.ValidateToken(token, tokenValidationParameters, out var securityToken); 111 | 112 | if (securityToken is not JwtSecurityToken jwtSecurityToken || 113 | !jwtSecurityToken.Header.Alg.Equals(SecurityAlgorithms.HmacSha256, StringComparison.InvariantCultureIgnoreCase)) 114 | { 115 | throw new SecurityTokenException("Invalid token"); 116 | } 117 | 118 | return principal; 119 | } 120 | 121 | private string GenerateRefreshToken() 122 | { 123 | // 创建一个随机的Token用做Refresh Token 124 | var randomNumber = new byte[32]; 125 | 126 | using var rng = RandomNumberGenerator.Create(); 127 | rng.GetBytes(randomNumber); 128 | 129 | return Convert.ToBase64String(randomNumber); 130 | } 131 | 132 | private SigningCredentials GetSigningCredentials() 133 | { 134 | // 出于演示的目的,我将SECRET值在这里fallback成了硬编码的字符串,实际环境中,最好是需要从环境变量中进行获取,而不应该写在代码中 135 | var key = Encoding.UTF8.GetBytes(Environment.GetEnvironmentVariable("SECRET") ?? "TodoListApiSecretKey"); 136 | var secret = new SymmetricSecurityKey(key); 137 | 138 | return new SigningCredentials(secret, SecurityAlgorithms.HmacSha256); 139 | } 140 | 141 | private async Task> GetClaims() 142 | { 143 | // 演示了返回用户名和Role两个claims 144 | var claims = new List 145 | { 146 | new(ClaimTypes.Name, User!.UserName), 147 | new(JwtRegisteredClaimNames.Iss, _jwtConfiguration.ValidIssuer ?? "TodoListApi"), 148 | new(JwtRegisteredClaimNames.Aud, _jwtConfiguration.ValidAudience ?? "http://localhost:5050") 149 | }; 150 | 151 | var roles = await _userManager.GetRolesAsync(User); 152 | claims.AddRange(roles.Select(role => new Claim(ClaimTypes.Role, role))); 153 | 154 | return claims; 155 | } 156 | 157 | private JwtSecurityToken GenerateTokenOptions(SigningCredentials signingCredentials, List claims) 158 | { 159 | // 配置JWT选项 160 | var tokenOptions = new JwtSecurityToken 161 | ( 162 | _jwtConfiguration.ValidIssuer, 163 | _jwtConfiguration.ValidAudience, 164 | claims, 165 | expires: DateTime.Now.AddMinutes(Convert.ToDouble(_jwtConfiguration.Expires)), 166 | signingCredentials: signingCredentials 167 | ); 168 | return tokenOptions; 169 | } 170 | } -------------------------------------------------------------------------------- /src/TodoList.Infrastructure/Log/ConfigureLogProvider.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Builder; 2 | using Microsoft.Extensions.Configuration; 3 | using Serilog; 4 | 5 | namespace TodoList.Infrastructure.Log; 6 | 7 | public static class ConfigureLogProvider 8 | { 9 | public static void ConfigureLog(this WebApplicationBuilder builder) 10 | { 11 | if (builder.Configuration.GetValue("UseFileToLog")) 12 | { 13 | // 配置同时输出到控制台和文件,并且指定文件名和文件转储方式(形如log-20211219.txt格式),转储文件保留的天数为15天,以及日志格式 14 | // 配置Enrich.FromLogContext()的目的是为了从日志上下文中获取一些关键信息诸如用户ID或请求ID,我们的应用中暂时不使用这些。 15 | Serilog.Log.Logger = new LoggerConfiguration() 16 | .Enrich.FromLogContext() 17 | .WriteTo.Console() 18 | .WriteTo.File( 19 | "logs/log-.txt", 20 | outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}", 21 | rollingInterval: RollingInterval.Day, 22 | retainedFileCountLimit: 15) 23 | .CreateLogger(); 24 | } 25 | else 26 | { 27 | // 仅配置控制台日志 28 | Serilog.Log.Logger = new LoggerConfiguration() 29 | .Enrich.FromLogContext() 30 | .WriteTo.Console() 31 | .CreateLogger(); 32 | } 33 | 34 | // 使用Serilog作为日志框架 35 | builder.Host.UseSerilog(); 36 | } 37 | } -------------------------------------------------------------------------------- /src/TodoList.Infrastructure/Migrations/20211220092915_SetupDb.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using Microsoft.EntityFrameworkCore; 3 | using Microsoft.EntityFrameworkCore.Infrastructure; 4 | using Microsoft.EntityFrameworkCore.Metadata; 5 | using Microsoft.EntityFrameworkCore.Migrations; 6 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 7 | using TodoList.Infrastructure.Persistence; 8 | 9 | #nullable disable 10 | 11 | namespace TodoList.Infrastructure.Migrations 12 | { 13 | [DbContext(typeof(TodoListDbContext))] 14 | [Migration("20211220092915_SetupDb")] 15 | partial class SetupDb 16 | { 17 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 18 | { 19 | #pragma warning disable 612, 618 20 | modelBuilder 21 | .HasAnnotation("ProductVersion", "6.0.1") 22 | .HasAnnotation("Relational:MaxIdentifierLength", 128); 23 | 24 | SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder, 1L, 1); 25 | #pragma warning restore 612, 618 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/TodoList.Infrastructure/Migrations/20211220092915_SetupDb.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore.Migrations; 2 | 3 | #nullable disable 4 | 5 | namespace TodoList.Infrastructure.Migrations 6 | { 7 | public partial class SetupDb : Migration 8 | { 9 | protected override void Up(MigrationBuilder migrationBuilder) 10 | { 11 | 12 | } 13 | 14 | protected override void Down(MigrationBuilder migrationBuilder) 15 | { 16 | 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/TodoList.Infrastructure/Migrations/20211222060615_AddEntities.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 | using TodoList.Infrastructure.Persistence; 9 | 10 | #nullable disable 11 | 12 | namespace TodoList.Infrastructure.Migrations 13 | { 14 | [DbContext(typeof(TodoListDbContext))] 15 | [Migration("20211222060615_AddEntities")] 16 | partial class AddEntities 17 | { 18 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 19 | { 20 | #pragma warning disable 612, 618 21 | modelBuilder 22 | .HasAnnotation("ProductVersion", "6.0.1") 23 | .HasAnnotation("Relational:MaxIdentifierLength", 128); 24 | 25 | SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder, 1L, 1); 26 | 27 | modelBuilder.Entity("TodoList.Domain.Entities.TodoItem", b => 28 | { 29 | b.Property("Id") 30 | .ValueGeneratedOnAdd() 31 | .HasColumnType("uniqueidentifier"); 32 | 33 | b.Property("Created") 34 | .HasColumnType("datetime2"); 35 | 36 | b.Property("CreatedBy") 37 | .HasColumnType("nvarchar(max)"); 38 | 39 | b.Property("Done") 40 | .HasColumnType("bit"); 41 | 42 | b.Property("LastModified") 43 | .HasColumnType("datetime2"); 44 | 45 | b.Property("LastModifiedBy") 46 | .HasColumnType("nvarchar(max)"); 47 | 48 | b.Property("ListId") 49 | .HasColumnType("uniqueidentifier"); 50 | 51 | b.Property("Priority") 52 | .HasColumnType("int"); 53 | 54 | b.Property("Title") 55 | .IsRequired() 56 | .HasMaxLength(200) 57 | .HasColumnType("nvarchar(200)"); 58 | 59 | b.HasKey("Id"); 60 | 61 | b.HasIndex("ListId"); 62 | 63 | b.ToTable("TodoItems"); 64 | }); 65 | 66 | modelBuilder.Entity("TodoList.Domain.Entities.TodoList", b => 67 | { 68 | b.Property("Id") 69 | .ValueGeneratedOnAdd() 70 | .HasColumnType("uniqueidentifier"); 71 | 72 | b.Property("Created") 73 | .HasColumnType("datetime2"); 74 | 75 | b.Property("CreatedBy") 76 | .HasColumnType("nvarchar(max)"); 77 | 78 | b.Property("LastModified") 79 | .HasColumnType("datetime2"); 80 | 81 | b.Property("LastModifiedBy") 82 | .HasColumnType("nvarchar(max)"); 83 | 84 | b.Property("Title") 85 | .IsRequired() 86 | .HasMaxLength(200) 87 | .HasColumnType("nvarchar(200)"); 88 | 89 | b.HasKey("Id"); 90 | 91 | b.ToTable("TodoLists"); 92 | }); 93 | 94 | modelBuilder.Entity("TodoList.Domain.Entities.TodoItem", b => 95 | { 96 | b.HasOne("TodoList.Domain.Entities.TodoList", "List") 97 | .WithMany("Items") 98 | .HasForeignKey("ListId") 99 | .OnDelete(DeleteBehavior.Cascade) 100 | .IsRequired(); 101 | 102 | b.Navigation("List"); 103 | }); 104 | 105 | modelBuilder.Entity("TodoList.Domain.Entities.TodoList", b => 106 | { 107 | b.OwnsOne("TodoList.Domain.ValueObjects.Colour", "Colour", b1 => 108 | { 109 | b1.Property("TodoListId") 110 | .HasColumnType("uniqueidentifier"); 111 | 112 | b1.Property("Code") 113 | .IsRequired() 114 | .HasColumnType("nvarchar(max)"); 115 | 116 | b1.HasKey("TodoListId"); 117 | 118 | b1.ToTable("TodoLists"); 119 | 120 | b1.WithOwner() 121 | .HasForeignKey("TodoListId"); 122 | }); 123 | 124 | b.Navigation("Colour") 125 | .IsRequired(); 126 | }); 127 | 128 | modelBuilder.Entity("TodoList.Domain.Entities.TodoList", b => 129 | { 130 | b.Navigation("Items"); 131 | }); 132 | #pragma warning restore 612, 618 133 | } 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /src/TodoList.Infrastructure/Migrations/20211222060615_AddEntities.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.EntityFrameworkCore.Migrations; 3 | 4 | #nullable disable 5 | 6 | namespace TodoList.Infrastructure.Migrations 7 | { 8 | public partial class AddEntities : Migration 9 | { 10 | protected override void Up(MigrationBuilder migrationBuilder) 11 | { 12 | migrationBuilder.CreateTable( 13 | name: "TodoLists", 14 | columns: table => new 15 | { 16 | Id = table.Column(type: "uniqueidentifier", nullable: false), 17 | Title = table.Column(type: "nvarchar(200)", maxLength: 200, nullable: false), 18 | Colour_Code = table.Column(type: "nvarchar(max)", nullable: false), 19 | Created = table.Column(type: "datetime2", nullable: false), 20 | CreatedBy = table.Column(type: "nvarchar(max)", nullable: true), 21 | LastModified = table.Column(type: "datetime2", nullable: true), 22 | LastModifiedBy = table.Column(type: "nvarchar(max)", nullable: true) 23 | }, 24 | constraints: table => 25 | { 26 | table.PrimaryKey("PK_TodoLists", x => x.Id); 27 | }); 28 | 29 | migrationBuilder.CreateTable( 30 | name: "TodoItems", 31 | columns: table => new 32 | { 33 | Id = table.Column(type: "uniqueidentifier", nullable: false), 34 | Title = table.Column(type: "nvarchar(200)", maxLength: 200, nullable: false), 35 | Priority = table.Column(type: "int", nullable: false), 36 | Done = table.Column(type: "bit", nullable: false), 37 | ListId = table.Column(type: "uniqueidentifier", nullable: false), 38 | Created = table.Column(type: "datetime2", nullable: false), 39 | CreatedBy = table.Column(type: "nvarchar(max)", nullable: true), 40 | LastModified = table.Column(type: "datetime2", nullable: true), 41 | LastModifiedBy = table.Column(type: "nvarchar(max)", nullable: true) 42 | }, 43 | constraints: table => 44 | { 45 | table.PrimaryKey("PK_TodoItems", x => x.Id); 46 | table.ForeignKey( 47 | name: "FK_TodoItems_TodoLists_ListId", 48 | column: x => x.ListId, 49 | principalTable: "TodoLists", 50 | principalColumn: "Id", 51 | onDelete: ReferentialAction.Cascade); 52 | }); 53 | 54 | migrationBuilder.CreateIndex( 55 | name: "IX_TodoItems_ListId", 56 | table: "TodoItems", 57 | column: "ListId"); 58 | } 59 | 60 | protected override void Down(MigrationBuilder migrationBuilder) 61 | { 62 | migrationBuilder.DropTable( 63 | name: "TodoItems"); 64 | 65 | migrationBuilder.DropTable( 66 | name: "TodoLists"); 67 | } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/TodoList.Infrastructure/Migrations/20220108073037_AddIdentitiesWithCredentials.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore.Migrations; 2 | 3 | #nullable disable 4 | 5 | namespace TodoList.Infrastructure.Migrations 6 | { 7 | public partial class AddIdentitiesWithCredentials : Migration 8 | { 9 | protected override void Up(MigrationBuilder migrationBuilder) 10 | { 11 | 12 | } 13 | 14 | protected override void Down(MigrationBuilder migrationBuilder) 15 | { 16 | 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/TodoList.Infrastructure/Migrations/20220108141927_UseIdentityIsteadofServer.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 | using TodoList.Infrastructure.Persistence; 9 | 10 | #nullable disable 11 | 12 | namespace TodoList.Infrastructure.Migrations 13 | { 14 | [DbContext(typeof(TodoListDbContext))] 15 | [Migration("20220108141927_UseIdentityIsteadofServer")] 16 | partial class UseIdentityIsteadofServer 17 | { 18 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 19 | { 20 | #pragma warning disable 612, 618 21 | modelBuilder 22 | .HasAnnotation("ProductVersion", "6.0.1") 23 | .HasAnnotation("Relational:MaxIdentifierLength", 128); 24 | 25 | SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder, 1L, 1); 26 | 27 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => 28 | { 29 | b.Property("Id") 30 | .HasColumnType("nvarchar(450)"); 31 | 32 | b.Property("ConcurrencyStamp") 33 | .IsConcurrencyToken() 34 | .HasColumnType("nvarchar(max)"); 35 | 36 | b.Property("Name") 37 | .HasMaxLength(256) 38 | .HasColumnType("nvarchar(256)"); 39 | 40 | b.Property("NormalizedName") 41 | .HasMaxLength(256) 42 | .HasColumnType("nvarchar(256)"); 43 | 44 | b.HasKey("Id"); 45 | 46 | b.HasIndex("NormalizedName") 47 | .IsUnique() 48 | .HasDatabaseName("RoleNameIndex") 49 | .HasFilter("[NormalizedName] IS NOT NULL"); 50 | 51 | b.ToTable("AspNetRoles", (string)null); 52 | }); 53 | 54 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => 55 | { 56 | b.Property("Id") 57 | .ValueGeneratedOnAdd() 58 | .HasColumnType("int"); 59 | 60 | SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id"), 1L, 1); 61 | 62 | b.Property("ClaimType") 63 | .HasColumnType("nvarchar(max)"); 64 | 65 | b.Property("ClaimValue") 66 | .HasColumnType("nvarchar(max)"); 67 | 68 | b.Property("RoleId") 69 | .IsRequired() 70 | .HasColumnType("nvarchar(450)"); 71 | 72 | b.HasKey("Id"); 73 | 74 | b.HasIndex("RoleId"); 75 | 76 | b.ToTable("AspNetRoleClaims", (string)null); 77 | }); 78 | 79 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => 80 | { 81 | b.Property("Id") 82 | .ValueGeneratedOnAdd() 83 | .HasColumnType("int"); 84 | 85 | SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id"), 1L, 1); 86 | 87 | b.Property("ClaimType") 88 | .HasColumnType("nvarchar(max)"); 89 | 90 | b.Property("ClaimValue") 91 | .HasColumnType("nvarchar(max)"); 92 | 93 | b.Property("UserId") 94 | .IsRequired() 95 | .HasColumnType("nvarchar(450)"); 96 | 97 | b.HasKey("Id"); 98 | 99 | b.HasIndex("UserId"); 100 | 101 | b.ToTable("AspNetUserClaims", (string)null); 102 | }); 103 | 104 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => 105 | { 106 | b.Property("LoginProvider") 107 | .HasMaxLength(128) 108 | .HasColumnType("nvarchar(128)"); 109 | 110 | b.Property("ProviderKey") 111 | .HasMaxLength(128) 112 | .HasColumnType("nvarchar(128)"); 113 | 114 | b.Property("ProviderDisplayName") 115 | .HasColumnType("nvarchar(max)"); 116 | 117 | b.Property("UserId") 118 | .IsRequired() 119 | .HasColumnType("nvarchar(450)"); 120 | 121 | b.HasKey("LoginProvider", "ProviderKey"); 122 | 123 | b.HasIndex("UserId"); 124 | 125 | b.ToTable("AspNetUserLogins", (string)null); 126 | }); 127 | 128 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => 129 | { 130 | b.Property("UserId") 131 | .HasColumnType("nvarchar(450)"); 132 | 133 | b.Property("RoleId") 134 | .HasColumnType("nvarchar(450)"); 135 | 136 | b.HasKey("UserId", "RoleId"); 137 | 138 | b.HasIndex("RoleId"); 139 | 140 | b.ToTable("AspNetUserRoles", (string)null); 141 | }); 142 | 143 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => 144 | { 145 | b.Property("UserId") 146 | .HasColumnType("nvarchar(450)"); 147 | 148 | b.Property("LoginProvider") 149 | .HasMaxLength(128) 150 | .HasColumnType("nvarchar(128)"); 151 | 152 | b.Property("Name") 153 | .HasMaxLength(128) 154 | .HasColumnType("nvarchar(128)"); 155 | 156 | b.Property("Value") 157 | .HasColumnType("nvarchar(max)"); 158 | 159 | b.HasKey("UserId", "LoginProvider", "Name"); 160 | 161 | b.ToTable("AspNetUserTokens", (string)null); 162 | }); 163 | 164 | modelBuilder.Entity("TodoList.Domain.Entities.TodoItem", b => 165 | { 166 | b.Property("Id") 167 | .ValueGeneratedOnAdd() 168 | .HasColumnType("uniqueidentifier"); 169 | 170 | b.Property("Created") 171 | .HasColumnType("datetime2"); 172 | 173 | b.Property("CreatedBy") 174 | .HasColumnType("nvarchar(max)"); 175 | 176 | b.Property("Done") 177 | .HasColumnType("bit"); 178 | 179 | b.Property("LastModified") 180 | .HasColumnType("datetime2"); 181 | 182 | b.Property("LastModifiedBy") 183 | .HasColumnType("nvarchar(max)"); 184 | 185 | b.Property("ListId") 186 | .HasColumnType("uniqueidentifier"); 187 | 188 | b.Property("Priority") 189 | .HasColumnType("int"); 190 | 191 | b.Property("Title") 192 | .IsRequired() 193 | .HasMaxLength(200) 194 | .HasColumnType("nvarchar(200)"); 195 | 196 | b.HasKey("Id"); 197 | 198 | b.HasIndex("ListId"); 199 | 200 | b.ToTable("TodoItems"); 201 | }); 202 | 203 | modelBuilder.Entity("TodoList.Domain.Entities.TodoList", b => 204 | { 205 | b.Property("Id") 206 | .ValueGeneratedOnAdd() 207 | .HasColumnType("uniqueidentifier"); 208 | 209 | b.Property("Created") 210 | .HasColumnType("datetime2"); 211 | 212 | b.Property("CreatedBy") 213 | .HasColumnType("nvarchar(max)"); 214 | 215 | b.Property("LastModified") 216 | .HasColumnType("datetime2"); 217 | 218 | b.Property("LastModifiedBy") 219 | .HasColumnType("nvarchar(max)"); 220 | 221 | b.Property("Title") 222 | .IsRequired() 223 | .HasMaxLength(200) 224 | .HasColumnType("nvarchar(200)"); 225 | 226 | b.HasKey("Id"); 227 | 228 | b.ToTable("TodoLists"); 229 | }); 230 | 231 | modelBuilder.Entity("TodoList.Infrastructure.Identity.ApplicationUser", b => 232 | { 233 | b.Property("Id") 234 | .HasColumnType("nvarchar(450)"); 235 | 236 | b.Property("AccessFailedCount") 237 | .HasColumnType("int"); 238 | 239 | b.Property("ConcurrencyStamp") 240 | .IsConcurrencyToken() 241 | .HasColumnType("nvarchar(max)"); 242 | 243 | b.Property("Email") 244 | .HasMaxLength(256) 245 | .HasColumnType("nvarchar(256)"); 246 | 247 | b.Property("EmailConfirmed") 248 | .HasColumnType("bit"); 249 | 250 | b.Property("LockoutEnabled") 251 | .HasColumnType("bit"); 252 | 253 | b.Property("LockoutEnd") 254 | .HasColumnType("datetimeoffset"); 255 | 256 | b.Property("NormalizedEmail") 257 | .HasMaxLength(256) 258 | .HasColumnType("nvarchar(256)"); 259 | 260 | b.Property("NormalizedUserName") 261 | .HasMaxLength(256) 262 | .HasColumnType("nvarchar(256)"); 263 | 264 | b.Property("PasswordHash") 265 | .HasColumnType("nvarchar(max)"); 266 | 267 | b.Property("PhoneNumber") 268 | .HasColumnType("nvarchar(max)"); 269 | 270 | b.Property("PhoneNumberConfirmed") 271 | .HasColumnType("bit"); 272 | 273 | b.Property("SecurityStamp") 274 | .HasColumnType("nvarchar(max)"); 275 | 276 | b.Property("TwoFactorEnabled") 277 | .HasColumnType("bit"); 278 | 279 | b.Property("UserName") 280 | .HasMaxLength(256) 281 | .HasColumnType("nvarchar(256)"); 282 | 283 | b.HasKey("Id"); 284 | 285 | b.HasIndex("NormalizedEmail") 286 | .HasDatabaseName("EmailIndex"); 287 | 288 | b.HasIndex("NormalizedUserName") 289 | .IsUnique() 290 | .HasDatabaseName("UserNameIndex") 291 | .HasFilter("[NormalizedUserName] IS NOT NULL"); 292 | 293 | b.ToTable("AspNetUsers", (string)null); 294 | }); 295 | 296 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => 297 | { 298 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) 299 | .WithMany() 300 | .HasForeignKey("RoleId") 301 | .OnDelete(DeleteBehavior.Cascade) 302 | .IsRequired(); 303 | }); 304 | 305 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => 306 | { 307 | b.HasOne("TodoList.Infrastructure.Identity.ApplicationUser", null) 308 | .WithMany() 309 | .HasForeignKey("UserId") 310 | .OnDelete(DeleteBehavior.Cascade) 311 | .IsRequired(); 312 | }); 313 | 314 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => 315 | { 316 | b.HasOne("TodoList.Infrastructure.Identity.ApplicationUser", null) 317 | .WithMany() 318 | .HasForeignKey("UserId") 319 | .OnDelete(DeleteBehavior.Cascade) 320 | .IsRequired(); 321 | }); 322 | 323 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => 324 | { 325 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) 326 | .WithMany() 327 | .HasForeignKey("RoleId") 328 | .OnDelete(DeleteBehavior.Cascade) 329 | .IsRequired(); 330 | 331 | b.HasOne("TodoList.Infrastructure.Identity.ApplicationUser", null) 332 | .WithMany() 333 | .HasForeignKey("UserId") 334 | .OnDelete(DeleteBehavior.Cascade) 335 | .IsRequired(); 336 | }); 337 | 338 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => 339 | { 340 | b.HasOne("TodoList.Infrastructure.Identity.ApplicationUser", null) 341 | .WithMany() 342 | .HasForeignKey("UserId") 343 | .OnDelete(DeleteBehavior.Cascade) 344 | .IsRequired(); 345 | }); 346 | 347 | modelBuilder.Entity("TodoList.Domain.Entities.TodoItem", b => 348 | { 349 | b.HasOne("TodoList.Domain.Entities.TodoList", "List") 350 | .WithMany("Items") 351 | .HasForeignKey("ListId") 352 | .OnDelete(DeleteBehavior.Cascade) 353 | .IsRequired(); 354 | 355 | b.Navigation("List"); 356 | }); 357 | 358 | modelBuilder.Entity("TodoList.Domain.Entities.TodoList", b => 359 | { 360 | b.OwnsOne("TodoList.Domain.ValueObjects.Colour", "Colour", b1 => 361 | { 362 | b1.Property("TodoListId") 363 | .HasColumnType("uniqueidentifier"); 364 | 365 | b1.Property("Code") 366 | .IsRequired() 367 | .HasColumnType("nvarchar(max)"); 368 | 369 | b1.HasKey("TodoListId"); 370 | 371 | b1.ToTable("TodoLists"); 372 | 373 | b1.WithOwner() 374 | .HasForeignKey("TodoListId"); 375 | }); 376 | 377 | b.Navigation("Colour") 378 | .IsRequired(); 379 | }); 380 | 381 | modelBuilder.Entity("TodoList.Domain.Entities.TodoList", b => 382 | { 383 | b.Navigation("Items"); 384 | }); 385 | #pragma warning restore 612, 618 386 | } 387 | } 388 | } 389 | -------------------------------------------------------------------------------- /src/TodoList.Infrastructure/Migrations/20220108141927_UseIdentityIsteadofServer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.EntityFrameworkCore.Migrations; 3 | 4 | #nullable disable 5 | 6 | namespace TodoList.Infrastructure.Migrations 7 | { 8 | public partial class UseIdentityIsteadofServer : Migration 9 | { 10 | protected override void Up(MigrationBuilder migrationBuilder) 11 | { 12 | migrationBuilder.DropTable( 13 | name: "DeviceCodes"); 14 | 15 | migrationBuilder.DropTable( 16 | name: "Keys"); 17 | 18 | migrationBuilder.DropTable( 19 | name: "PersistedGrants"); 20 | } 21 | 22 | protected override void Down(MigrationBuilder migrationBuilder) 23 | { 24 | migrationBuilder.CreateTable( 25 | name: "DeviceCodes", 26 | columns: table => new 27 | { 28 | UserCode = table.Column(type: "nvarchar(200)", maxLength: 200, nullable: false), 29 | ClientId = table.Column(type: "nvarchar(200)", maxLength: 200, nullable: false), 30 | CreationTime = table.Column(type: "datetime2", nullable: false), 31 | Data = table.Column(type: "nvarchar(max)", maxLength: 50000, nullable: false), 32 | Description = table.Column(type: "nvarchar(200)", maxLength: 200, nullable: true), 33 | DeviceCode = table.Column(type: "nvarchar(200)", maxLength: 200, nullable: false), 34 | Expiration = table.Column(type: "datetime2", nullable: false), 35 | SessionId = table.Column(type: "nvarchar(100)", maxLength: 100, nullable: true), 36 | SubjectId = table.Column(type: "nvarchar(200)", maxLength: 200, nullable: true) 37 | }, 38 | constraints: table => 39 | { 40 | table.PrimaryKey("PK_DeviceCodes", x => x.UserCode); 41 | }); 42 | 43 | migrationBuilder.CreateTable( 44 | name: "Keys", 45 | columns: table => new 46 | { 47 | Id = table.Column(type: "nvarchar(450)", nullable: false), 48 | Algorithm = table.Column(type: "nvarchar(100)", maxLength: 100, nullable: false), 49 | Created = table.Column(type: "datetime2", nullable: false), 50 | Data = table.Column(type: "nvarchar(max)", nullable: false), 51 | DataProtected = table.Column(type: "bit", nullable: false), 52 | IsX509Certificate = table.Column(type: "bit", nullable: false), 53 | Use = table.Column(type: "nvarchar(450)", nullable: true), 54 | Version = table.Column(type: "int", nullable: false) 55 | }, 56 | constraints: table => 57 | { 58 | table.PrimaryKey("PK_Keys", x => x.Id); 59 | }); 60 | 61 | migrationBuilder.CreateTable( 62 | name: "PersistedGrants", 63 | columns: table => new 64 | { 65 | Key = table.Column(type: "nvarchar(200)", maxLength: 200, nullable: false), 66 | ClientId = table.Column(type: "nvarchar(200)", maxLength: 200, nullable: false), 67 | ConsumedTime = table.Column(type: "datetime2", nullable: true), 68 | CreationTime = table.Column(type: "datetime2", nullable: false), 69 | Data = table.Column(type: "nvarchar(max)", maxLength: 50000, nullable: false), 70 | Description = table.Column(type: "nvarchar(200)", maxLength: 200, nullable: true), 71 | Expiration = table.Column(type: "datetime2", nullable: true), 72 | SessionId = table.Column(type: "nvarchar(100)", maxLength: 100, nullable: true), 73 | SubjectId = table.Column(type: "nvarchar(200)", maxLength: 200, nullable: true), 74 | Type = table.Column(type: "nvarchar(50)", maxLength: 50, nullable: false) 75 | }, 76 | constraints: table => 77 | { 78 | table.PrimaryKey("PK_PersistedGrants", x => x.Key); 79 | }); 80 | 81 | migrationBuilder.CreateIndex( 82 | name: "IX_DeviceCodes_DeviceCode", 83 | table: "DeviceCodes", 84 | column: "DeviceCode", 85 | unique: true); 86 | 87 | migrationBuilder.CreateIndex( 88 | name: "IX_DeviceCodes_Expiration", 89 | table: "DeviceCodes", 90 | column: "Expiration"); 91 | 92 | migrationBuilder.CreateIndex( 93 | name: "IX_Keys_Use", 94 | table: "Keys", 95 | column: "Use"); 96 | 97 | migrationBuilder.CreateIndex( 98 | name: "IX_PersistedGrants_ConsumedTime", 99 | table: "PersistedGrants", 100 | column: "ConsumedTime"); 101 | 102 | migrationBuilder.CreateIndex( 103 | name: "IX_PersistedGrants_Expiration", 104 | table: "PersistedGrants", 105 | column: "Expiration"); 106 | 107 | migrationBuilder.CreateIndex( 108 | name: "IX_PersistedGrants_SubjectId_ClientId_Type", 109 | table: "PersistedGrants", 110 | columns: new[] { "SubjectId", "ClientId", "Type" }); 111 | 112 | migrationBuilder.CreateIndex( 113 | name: "IX_PersistedGrants_SubjectId_SessionId_Type", 114 | table: "PersistedGrants", 115 | columns: new[] { "SubjectId", "SessionId", "Type" }); 116 | } 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /src/TodoList.Infrastructure/Migrations/20220109065325_AddRefreshToken.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 | using TodoList.Infrastructure.Persistence; 9 | 10 | #nullable disable 11 | 12 | namespace TodoList.Infrastructure.Migrations 13 | { 14 | [DbContext(typeof(TodoListDbContext))] 15 | [Migration("20220109065325_AddRefreshToken")] 16 | partial class AddRefreshToken 17 | { 18 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 19 | { 20 | #pragma warning disable 612, 618 21 | modelBuilder 22 | .HasAnnotation("ProductVersion", "6.0.1") 23 | .HasAnnotation("Relational:MaxIdentifierLength", 128); 24 | 25 | SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder, 1L, 1); 26 | 27 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => 28 | { 29 | b.Property("Id") 30 | .HasColumnType("nvarchar(450)"); 31 | 32 | b.Property("ConcurrencyStamp") 33 | .IsConcurrencyToken() 34 | .HasColumnType("nvarchar(max)"); 35 | 36 | b.Property("Name") 37 | .HasMaxLength(256) 38 | .HasColumnType("nvarchar(256)"); 39 | 40 | b.Property("NormalizedName") 41 | .HasMaxLength(256) 42 | .HasColumnType("nvarchar(256)"); 43 | 44 | b.HasKey("Id"); 45 | 46 | b.HasIndex("NormalizedName") 47 | .IsUnique() 48 | .HasDatabaseName("RoleNameIndex") 49 | .HasFilter("[NormalizedName] IS NOT NULL"); 50 | 51 | b.ToTable("AspNetRoles", (string)null); 52 | }); 53 | 54 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => 55 | { 56 | b.Property("Id") 57 | .ValueGeneratedOnAdd() 58 | .HasColumnType("int"); 59 | 60 | SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id"), 1L, 1); 61 | 62 | b.Property("ClaimType") 63 | .HasColumnType("nvarchar(max)"); 64 | 65 | b.Property("ClaimValue") 66 | .HasColumnType("nvarchar(max)"); 67 | 68 | b.Property("RoleId") 69 | .IsRequired() 70 | .HasColumnType("nvarchar(450)"); 71 | 72 | b.HasKey("Id"); 73 | 74 | b.HasIndex("RoleId"); 75 | 76 | b.ToTable("AspNetRoleClaims", (string)null); 77 | }); 78 | 79 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => 80 | { 81 | b.Property("Id") 82 | .ValueGeneratedOnAdd() 83 | .HasColumnType("int"); 84 | 85 | SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id"), 1L, 1); 86 | 87 | b.Property("ClaimType") 88 | .HasColumnType("nvarchar(max)"); 89 | 90 | b.Property("ClaimValue") 91 | .HasColumnType("nvarchar(max)"); 92 | 93 | b.Property("UserId") 94 | .IsRequired() 95 | .HasColumnType("nvarchar(450)"); 96 | 97 | b.HasKey("Id"); 98 | 99 | b.HasIndex("UserId"); 100 | 101 | b.ToTable("AspNetUserClaims", (string)null); 102 | }); 103 | 104 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => 105 | { 106 | b.Property("LoginProvider") 107 | .HasColumnType("nvarchar(450)"); 108 | 109 | b.Property("ProviderKey") 110 | .HasColumnType("nvarchar(450)"); 111 | 112 | b.Property("ProviderDisplayName") 113 | .HasColumnType("nvarchar(max)"); 114 | 115 | b.Property("UserId") 116 | .IsRequired() 117 | .HasColumnType("nvarchar(450)"); 118 | 119 | b.HasKey("LoginProvider", "ProviderKey"); 120 | 121 | b.HasIndex("UserId"); 122 | 123 | b.ToTable("AspNetUserLogins", (string)null); 124 | }); 125 | 126 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => 127 | { 128 | b.Property("UserId") 129 | .HasColumnType("nvarchar(450)"); 130 | 131 | b.Property("RoleId") 132 | .HasColumnType("nvarchar(450)"); 133 | 134 | b.HasKey("UserId", "RoleId"); 135 | 136 | b.HasIndex("RoleId"); 137 | 138 | b.ToTable("AspNetUserRoles", (string)null); 139 | }); 140 | 141 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => 142 | { 143 | b.Property("UserId") 144 | .HasColumnType("nvarchar(450)"); 145 | 146 | b.Property("LoginProvider") 147 | .HasColumnType("nvarchar(450)"); 148 | 149 | b.Property("Name") 150 | .HasColumnType("nvarchar(450)"); 151 | 152 | b.Property("Value") 153 | .HasColumnType("nvarchar(max)"); 154 | 155 | b.HasKey("UserId", "LoginProvider", "Name"); 156 | 157 | b.ToTable("AspNetUserTokens", (string)null); 158 | }); 159 | 160 | modelBuilder.Entity("TodoList.Domain.Entities.TodoItem", b => 161 | { 162 | b.Property("Id") 163 | .ValueGeneratedOnAdd() 164 | .HasColumnType("uniqueidentifier"); 165 | 166 | b.Property("Created") 167 | .HasColumnType("datetime2"); 168 | 169 | b.Property("CreatedBy") 170 | .HasColumnType("nvarchar(max)"); 171 | 172 | b.Property("Done") 173 | .HasColumnType("bit"); 174 | 175 | b.Property("LastModified") 176 | .HasColumnType("datetime2"); 177 | 178 | b.Property("LastModifiedBy") 179 | .HasColumnType("nvarchar(max)"); 180 | 181 | b.Property("ListId") 182 | .HasColumnType("uniqueidentifier"); 183 | 184 | b.Property("Priority") 185 | .HasColumnType("int"); 186 | 187 | b.Property("Title") 188 | .IsRequired() 189 | .HasMaxLength(200) 190 | .HasColumnType("nvarchar(200)"); 191 | 192 | b.HasKey("Id"); 193 | 194 | b.HasIndex("ListId"); 195 | 196 | b.ToTable("TodoItems"); 197 | }); 198 | 199 | modelBuilder.Entity("TodoList.Domain.Entities.TodoList", b => 200 | { 201 | b.Property("Id") 202 | .ValueGeneratedOnAdd() 203 | .HasColumnType("uniqueidentifier"); 204 | 205 | b.Property("Created") 206 | .HasColumnType("datetime2"); 207 | 208 | b.Property("CreatedBy") 209 | .HasColumnType("nvarchar(max)"); 210 | 211 | b.Property("LastModified") 212 | .HasColumnType("datetime2"); 213 | 214 | b.Property("LastModifiedBy") 215 | .HasColumnType("nvarchar(max)"); 216 | 217 | b.Property("Title") 218 | .IsRequired() 219 | .HasMaxLength(200) 220 | .HasColumnType("nvarchar(200)"); 221 | 222 | b.HasKey("Id"); 223 | 224 | b.ToTable("TodoLists"); 225 | }); 226 | 227 | modelBuilder.Entity("TodoList.Infrastructure.Identity.ApplicationUser", b => 228 | { 229 | b.Property("Id") 230 | .HasColumnType("nvarchar(450)"); 231 | 232 | b.Property("AccessFailedCount") 233 | .HasColumnType("int"); 234 | 235 | b.Property("ConcurrencyStamp") 236 | .IsConcurrencyToken() 237 | .HasColumnType("nvarchar(max)"); 238 | 239 | b.Property("Email") 240 | .HasMaxLength(256) 241 | .HasColumnType("nvarchar(256)"); 242 | 243 | b.Property("EmailConfirmed") 244 | .HasColumnType("bit"); 245 | 246 | b.Property("LockoutEnabled") 247 | .HasColumnType("bit"); 248 | 249 | b.Property("LockoutEnd") 250 | .HasColumnType("datetimeoffset"); 251 | 252 | b.Property("NormalizedEmail") 253 | .HasMaxLength(256) 254 | .HasColumnType("nvarchar(256)"); 255 | 256 | b.Property("NormalizedUserName") 257 | .HasMaxLength(256) 258 | .HasColumnType("nvarchar(256)"); 259 | 260 | b.Property("PasswordHash") 261 | .HasColumnType("nvarchar(max)"); 262 | 263 | b.Property("PhoneNumber") 264 | .HasColumnType("nvarchar(max)"); 265 | 266 | b.Property("PhoneNumberConfirmed") 267 | .HasColumnType("bit"); 268 | 269 | b.Property("RefreshToken") 270 | .HasColumnType("nvarchar(max)"); 271 | 272 | b.Property("RefreshTokenExpiryTime") 273 | .HasColumnType("datetime2"); 274 | 275 | b.Property("SecurityStamp") 276 | .HasColumnType("nvarchar(max)"); 277 | 278 | b.Property("TwoFactorEnabled") 279 | .HasColumnType("bit"); 280 | 281 | b.Property("UserName") 282 | .HasMaxLength(256) 283 | .HasColumnType("nvarchar(256)"); 284 | 285 | b.HasKey("Id"); 286 | 287 | b.HasIndex("NormalizedEmail") 288 | .HasDatabaseName("EmailIndex"); 289 | 290 | b.HasIndex("NormalizedUserName") 291 | .IsUnique() 292 | .HasDatabaseName("UserNameIndex") 293 | .HasFilter("[NormalizedUserName] IS NOT NULL"); 294 | 295 | b.ToTable("AspNetUsers", (string)null); 296 | }); 297 | 298 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => 299 | { 300 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) 301 | .WithMany() 302 | .HasForeignKey("RoleId") 303 | .OnDelete(DeleteBehavior.Cascade) 304 | .IsRequired(); 305 | }); 306 | 307 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => 308 | { 309 | b.HasOne("TodoList.Infrastructure.Identity.ApplicationUser", null) 310 | .WithMany() 311 | .HasForeignKey("UserId") 312 | .OnDelete(DeleteBehavior.Cascade) 313 | .IsRequired(); 314 | }); 315 | 316 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => 317 | { 318 | b.HasOne("TodoList.Infrastructure.Identity.ApplicationUser", null) 319 | .WithMany() 320 | .HasForeignKey("UserId") 321 | .OnDelete(DeleteBehavior.Cascade) 322 | .IsRequired(); 323 | }); 324 | 325 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => 326 | { 327 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) 328 | .WithMany() 329 | .HasForeignKey("RoleId") 330 | .OnDelete(DeleteBehavior.Cascade) 331 | .IsRequired(); 332 | 333 | b.HasOne("TodoList.Infrastructure.Identity.ApplicationUser", null) 334 | .WithMany() 335 | .HasForeignKey("UserId") 336 | .OnDelete(DeleteBehavior.Cascade) 337 | .IsRequired(); 338 | }); 339 | 340 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => 341 | { 342 | b.HasOne("TodoList.Infrastructure.Identity.ApplicationUser", null) 343 | .WithMany() 344 | .HasForeignKey("UserId") 345 | .OnDelete(DeleteBehavior.Cascade) 346 | .IsRequired(); 347 | }); 348 | 349 | modelBuilder.Entity("TodoList.Domain.Entities.TodoItem", b => 350 | { 351 | b.HasOne("TodoList.Domain.Entities.TodoList", "List") 352 | .WithMany("Items") 353 | .HasForeignKey("ListId") 354 | .OnDelete(DeleteBehavior.Cascade) 355 | .IsRequired(); 356 | 357 | b.Navigation("List"); 358 | }); 359 | 360 | modelBuilder.Entity("TodoList.Domain.Entities.TodoList", b => 361 | { 362 | b.OwnsOne("TodoList.Domain.ValueObjects.Colour", "Colour", b1 => 363 | { 364 | b1.Property("TodoListId") 365 | .HasColumnType("uniqueidentifier"); 366 | 367 | b1.Property("Code") 368 | .IsRequired() 369 | .HasColumnType("nvarchar(max)"); 370 | 371 | b1.HasKey("TodoListId"); 372 | 373 | b1.ToTable("TodoLists"); 374 | 375 | b1.WithOwner() 376 | .HasForeignKey("TodoListId"); 377 | }); 378 | 379 | b.Navigation("Colour") 380 | .IsRequired(); 381 | }); 382 | 383 | modelBuilder.Entity("TodoList.Domain.Entities.TodoList", b => 384 | { 385 | b.Navigation("Items"); 386 | }); 387 | #pragma warning restore 612, 618 388 | } 389 | } 390 | } 391 | -------------------------------------------------------------------------------- /src/TodoList.Infrastructure/Migrations/20220109065325_AddRefreshToken.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.EntityFrameworkCore.Migrations; 3 | 4 | #nullable disable 5 | 6 | namespace TodoList.Infrastructure.Migrations 7 | { 8 | public partial class AddRefreshToken : Migration 9 | { 10 | protected override void Up(MigrationBuilder migrationBuilder) 11 | { 12 | migrationBuilder.AlterColumn( 13 | name: "Name", 14 | table: "AspNetUserTokens", 15 | type: "nvarchar(450)", 16 | nullable: false, 17 | oldClrType: typeof(string), 18 | oldType: "nvarchar(128)", 19 | oldMaxLength: 128); 20 | 21 | migrationBuilder.AlterColumn( 22 | name: "LoginProvider", 23 | table: "AspNetUserTokens", 24 | type: "nvarchar(450)", 25 | nullable: false, 26 | oldClrType: typeof(string), 27 | oldType: "nvarchar(128)", 28 | oldMaxLength: 128); 29 | 30 | migrationBuilder.AddColumn( 31 | name: "RefreshToken", 32 | table: "AspNetUsers", 33 | type: "nvarchar(max)", 34 | nullable: true); 35 | 36 | migrationBuilder.AddColumn( 37 | name: "RefreshTokenExpiryTime", 38 | table: "AspNetUsers", 39 | type: "datetime2", 40 | nullable: false, 41 | defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)); 42 | 43 | migrationBuilder.AlterColumn( 44 | name: "ProviderKey", 45 | table: "AspNetUserLogins", 46 | type: "nvarchar(450)", 47 | nullable: false, 48 | oldClrType: typeof(string), 49 | oldType: "nvarchar(128)", 50 | oldMaxLength: 128); 51 | 52 | migrationBuilder.AlterColumn( 53 | name: "LoginProvider", 54 | table: "AspNetUserLogins", 55 | type: "nvarchar(450)", 56 | nullable: false, 57 | oldClrType: typeof(string), 58 | oldType: "nvarchar(128)", 59 | oldMaxLength: 128); 60 | } 61 | 62 | protected override void Down(MigrationBuilder migrationBuilder) 63 | { 64 | migrationBuilder.DropColumn( 65 | name: "RefreshToken", 66 | table: "AspNetUsers"); 67 | 68 | migrationBuilder.DropColumn( 69 | name: "RefreshTokenExpiryTime", 70 | table: "AspNetUsers"); 71 | 72 | migrationBuilder.AlterColumn( 73 | name: "Name", 74 | table: "AspNetUserTokens", 75 | type: "nvarchar(128)", 76 | maxLength: 128, 77 | nullable: false, 78 | oldClrType: typeof(string), 79 | oldType: "nvarchar(450)"); 80 | 81 | migrationBuilder.AlterColumn( 82 | name: "LoginProvider", 83 | table: "AspNetUserTokens", 84 | type: "nvarchar(128)", 85 | maxLength: 128, 86 | nullable: false, 87 | oldClrType: typeof(string), 88 | oldType: "nvarchar(450)"); 89 | 90 | migrationBuilder.AlterColumn( 91 | name: "ProviderKey", 92 | table: "AspNetUserLogins", 93 | type: "nvarchar(128)", 94 | maxLength: 128, 95 | nullable: false, 96 | oldClrType: typeof(string), 97 | oldType: "nvarchar(450)"); 98 | 99 | migrationBuilder.AlterColumn( 100 | name: "LoginProvider", 101 | table: "AspNetUserLogins", 102 | type: "nvarchar(128)", 103 | maxLength: 128, 104 | nullable: false, 105 | oldClrType: typeof(string), 106 | oldType: "nvarchar(450)"); 107 | } 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /src/TodoList.Infrastructure/Migrations/TodoListDbContextModelSnapshot.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 | using TodoList.Infrastructure.Persistence; 8 | 9 | #nullable disable 10 | 11 | namespace TodoList.Infrastructure.Migrations 12 | { 13 | [DbContext(typeof(TodoListDbContext))] 14 | partial class TodoListDbContextModelSnapshot : ModelSnapshot 15 | { 16 | protected override void BuildModel(ModelBuilder modelBuilder) 17 | { 18 | #pragma warning disable 612, 618 19 | modelBuilder 20 | .HasAnnotation("ProductVersion", "6.0.1") 21 | .HasAnnotation("Relational:MaxIdentifierLength", 128); 22 | 23 | SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder, 1L, 1); 24 | 25 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => 26 | { 27 | b.Property("Id") 28 | .HasColumnType("nvarchar(450)"); 29 | 30 | b.Property("ConcurrencyStamp") 31 | .IsConcurrencyToken() 32 | .HasColumnType("nvarchar(max)"); 33 | 34 | b.Property("Name") 35 | .HasMaxLength(256) 36 | .HasColumnType("nvarchar(256)"); 37 | 38 | b.Property("NormalizedName") 39 | .HasMaxLength(256) 40 | .HasColumnType("nvarchar(256)"); 41 | 42 | b.HasKey("Id"); 43 | 44 | b.HasIndex("NormalizedName") 45 | .IsUnique() 46 | .HasDatabaseName("RoleNameIndex") 47 | .HasFilter("[NormalizedName] IS NOT NULL"); 48 | 49 | b.ToTable("AspNetRoles", (string)null); 50 | }); 51 | 52 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => 53 | { 54 | b.Property("Id") 55 | .ValueGeneratedOnAdd() 56 | .HasColumnType("int"); 57 | 58 | SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id"), 1L, 1); 59 | 60 | b.Property("ClaimType") 61 | .HasColumnType("nvarchar(max)"); 62 | 63 | b.Property("ClaimValue") 64 | .HasColumnType("nvarchar(max)"); 65 | 66 | b.Property("RoleId") 67 | .IsRequired() 68 | .HasColumnType("nvarchar(450)"); 69 | 70 | b.HasKey("Id"); 71 | 72 | b.HasIndex("RoleId"); 73 | 74 | b.ToTable("AspNetRoleClaims", (string)null); 75 | }); 76 | 77 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => 78 | { 79 | b.Property("Id") 80 | .ValueGeneratedOnAdd() 81 | .HasColumnType("int"); 82 | 83 | SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id"), 1L, 1); 84 | 85 | b.Property("ClaimType") 86 | .HasColumnType("nvarchar(max)"); 87 | 88 | b.Property("ClaimValue") 89 | .HasColumnType("nvarchar(max)"); 90 | 91 | b.Property("UserId") 92 | .IsRequired() 93 | .HasColumnType("nvarchar(450)"); 94 | 95 | b.HasKey("Id"); 96 | 97 | b.HasIndex("UserId"); 98 | 99 | b.ToTable("AspNetUserClaims", (string)null); 100 | }); 101 | 102 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => 103 | { 104 | b.Property("LoginProvider") 105 | .HasColumnType("nvarchar(450)"); 106 | 107 | b.Property("ProviderKey") 108 | .HasColumnType("nvarchar(450)"); 109 | 110 | b.Property("ProviderDisplayName") 111 | .HasColumnType("nvarchar(max)"); 112 | 113 | b.Property("UserId") 114 | .IsRequired() 115 | .HasColumnType("nvarchar(450)"); 116 | 117 | b.HasKey("LoginProvider", "ProviderKey"); 118 | 119 | b.HasIndex("UserId"); 120 | 121 | b.ToTable("AspNetUserLogins", (string)null); 122 | }); 123 | 124 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => 125 | { 126 | b.Property("UserId") 127 | .HasColumnType("nvarchar(450)"); 128 | 129 | b.Property("RoleId") 130 | .HasColumnType("nvarchar(450)"); 131 | 132 | b.HasKey("UserId", "RoleId"); 133 | 134 | b.HasIndex("RoleId"); 135 | 136 | b.ToTable("AspNetUserRoles", (string)null); 137 | }); 138 | 139 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => 140 | { 141 | b.Property("UserId") 142 | .HasColumnType("nvarchar(450)"); 143 | 144 | b.Property("LoginProvider") 145 | .HasColumnType("nvarchar(450)"); 146 | 147 | b.Property("Name") 148 | .HasColumnType("nvarchar(450)"); 149 | 150 | b.Property("Value") 151 | .HasColumnType("nvarchar(max)"); 152 | 153 | b.HasKey("UserId", "LoginProvider", "Name"); 154 | 155 | b.ToTable("AspNetUserTokens", (string)null); 156 | }); 157 | 158 | modelBuilder.Entity("TodoList.Domain.Entities.TodoItem", b => 159 | { 160 | b.Property("Id") 161 | .ValueGeneratedOnAdd() 162 | .HasColumnType("uniqueidentifier"); 163 | 164 | b.Property("Created") 165 | .HasColumnType("datetime2"); 166 | 167 | b.Property("CreatedBy") 168 | .HasColumnType("nvarchar(max)"); 169 | 170 | b.Property("Done") 171 | .HasColumnType("bit"); 172 | 173 | b.Property("LastModified") 174 | .HasColumnType("datetime2"); 175 | 176 | b.Property("LastModifiedBy") 177 | .HasColumnType("nvarchar(max)"); 178 | 179 | b.Property("ListId") 180 | .HasColumnType("uniqueidentifier"); 181 | 182 | b.Property("Priority") 183 | .HasColumnType("int"); 184 | 185 | b.Property("Title") 186 | .IsRequired() 187 | .HasMaxLength(200) 188 | .HasColumnType("nvarchar(200)"); 189 | 190 | b.HasKey("Id"); 191 | 192 | b.HasIndex("ListId"); 193 | 194 | b.ToTable("TodoItems"); 195 | }); 196 | 197 | modelBuilder.Entity("TodoList.Domain.Entities.TodoList", b => 198 | { 199 | b.Property("Id") 200 | .ValueGeneratedOnAdd() 201 | .HasColumnType("uniqueidentifier"); 202 | 203 | b.Property("Created") 204 | .HasColumnType("datetime2"); 205 | 206 | b.Property("CreatedBy") 207 | .HasColumnType("nvarchar(max)"); 208 | 209 | b.Property("LastModified") 210 | .HasColumnType("datetime2"); 211 | 212 | b.Property("LastModifiedBy") 213 | .HasColumnType("nvarchar(max)"); 214 | 215 | b.Property("Title") 216 | .IsRequired() 217 | .HasMaxLength(200) 218 | .HasColumnType("nvarchar(200)"); 219 | 220 | b.HasKey("Id"); 221 | 222 | b.ToTable("TodoLists"); 223 | }); 224 | 225 | modelBuilder.Entity("TodoList.Infrastructure.Identity.ApplicationUser", b => 226 | { 227 | b.Property("Id") 228 | .HasColumnType("nvarchar(450)"); 229 | 230 | b.Property("AccessFailedCount") 231 | .HasColumnType("int"); 232 | 233 | b.Property("ConcurrencyStamp") 234 | .IsConcurrencyToken() 235 | .HasColumnType("nvarchar(max)"); 236 | 237 | b.Property("Email") 238 | .HasMaxLength(256) 239 | .HasColumnType("nvarchar(256)"); 240 | 241 | b.Property("EmailConfirmed") 242 | .HasColumnType("bit"); 243 | 244 | b.Property("LockoutEnabled") 245 | .HasColumnType("bit"); 246 | 247 | b.Property("LockoutEnd") 248 | .HasColumnType("datetimeoffset"); 249 | 250 | b.Property("NormalizedEmail") 251 | .HasMaxLength(256) 252 | .HasColumnType("nvarchar(256)"); 253 | 254 | b.Property("NormalizedUserName") 255 | .HasMaxLength(256) 256 | .HasColumnType("nvarchar(256)"); 257 | 258 | b.Property("PasswordHash") 259 | .HasColumnType("nvarchar(max)"); 260 | 261 | b.Property("PhoneNumber") 262 | .HasColumnType("nvarchar(max)"); 263 | 264 | b.Property("PhoneNumberConfirmed") 265 | .HasColumnType("bit"); 266 | 267 | b.Property("RefreshToken") 268 | .HasColumnType("nvarchar(max)"); 269 | 270 | b.Property("RefreshTokenExpiryTime") 271 | .HasColumnType("datetime2"); 272 | 273 | b.Property("SecurityStamp") 274 | .HasColumnType("nvarchar(max)"); 275 | 276 | b.Property("TwoFactorEnabled") 277 | .HasColumnType("bit"); 278 | 279 | b.Property("UserName") 280 | .HasMaxLength(256) 281 | .HasColumnType("nvarchar(256)"); 282 | 283 | b.HasKey("Id"); 284 | 285 | b.HasIndex("NormalizedEmail") 286 | .HasDatabaseName("EmailIndex"); 287 | 288 | b.HasIndex("NormalizedUserName") 289 | .IsUnique() 290 | .HasDatabaseName("UserNameIndex") 291 | .HasFilter("[NormalizedUserName] IS NOT NULL"); 292 | 293 | b.ToTable("AspNetUsers", (string)null); 294 | }); 295 | 296 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => 297 | { 298 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) 299 | .WithMany() 300 | .HasForeignKey("RoleId") 301 | .OnDelete(DeleteBehavior.Cascade) 302 | .IsRequired(); 303 | }); 304 | 305 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => 306 | { 307 | b.HasOne("TodoList.Infrastructure.Identity.ApplicationUser", null) 308 | .WithMany() 309 | .HasForeignKey("UserId") 310 | .OnDelete(DeleteBehavior.Cascade) 311 | .IsRequired(); 312 | }); 313 | 314 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => 315 | { 316 | b.HasOne("TodoList.Infrastructure.Identity.ApplicationUser", null) 317 | .WithMany() 318 | .HasForeignKey("UserId") 319 | .OnDelete(DeleteBehavior.Cascade) 320 | .IsRequired(); 321 | }); 322 | 323 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => 324 | { 325 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) 326 | .WithMany() 327 | .HasForeignKey("RoleId") 328 | .OnDelete(DeleteBehavior.Cascade) 329 | .IsRequired(); 330 | 331 | b.HasOne("TodoList.Infrastructure.Identity.ApplicationUser", null) 332 | .WithMany() 333 | .HasForeignKey("UserId") 334 | .OnDelete(DeleteBehavior.Cascade) 335 | .IsRequired(); 336 | }); 337 | 338 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => 339 | { 340 | b.HasOne("TodoList.Infrastructure.Identity.ApplicationUser", null) 341 | .WithMany() 342 | .HasForeignKey("UserId") 343 | .OnDelete(DeleteBehavior.Cascade) 344 | .IsRequired(); 345 | }); 346 | 347 | modelBuilder.Entity("TodoList.Domain.Entities.TodoItem", b => 348 | { 349 | b.HasOne("TodoList.Domain.Entities.TodoList", "List") 350 | .WithMany("Items") 351 | .HasForeignKey("ListId") 352 | .OnDelete(DeleteBehavior.Cascade) 353 | .IsRequired(); 354 | 355 | b.Navigation("List"); 356 | }); 357 | 358 | modelBuilder.Entity("TodoList.Domain.Entities.TodoList", b => 359 | { 360 | b.OwnsOne("TodoList.Domain.ValueObjects.Colour", "Colour", b1 => 361 | { 362 | b1.Property("TodoListId") 363 | .HasColumnType("uniqueidentifier"); 364 | 365 | b1.Property("Code") 366 | .IsRequired() 367 | .HasColumnType("nvarchar(max)"); 368 | 369 | b1.HasKey("TodoListId"); 370 | 371 | b1.ToTable("TodoLists"); 372 | 373 | b1.WithOwner() 374 | .HasForeignKey("TodoListId"); 375 | }); 376 | 377 | b.Navigation("Colour") 378 | .IsRequired(); 379 | }); 380 | 381 | modelBuilder.Entity("TodoList.Domain.Entities.TodoList", b => 382 | { 383 | b.Navigation("Items"); 384 | }); 385 | #pragma warning restore 612, 618 386 | } 387 | } 388 | } 389 | -------------------------------------------------------------------------------- /src/TodoList.Infrastructure/Persistence/Configurations/TodoItemConfiguration.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using Microsoft.EntityFrameworkCore.Metadata.Builders; 3 | using TodoList.Domain.Entities; 4 | 5 | namespace TodoList.Infrastructure.Persistence.Configurations; 6 | 7 | public class TodoItemConfiguration : IEntityTypeConfiguration 8 | { 9 | public void Configure(EntityTypeBuilder builder) 10 | { 11 | builder.Ignore(e => e.DomainEvents); 12 | 13 | builder.Property(t => t.Title) 14 | .HasMaxLength(200) 15 | .IsRequired(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/TodoList.Infrastructure/Persistence/Configurations/TodoListConfiguration.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using Microsoft.EntityFrameworkCore.Metadata.Builders; 3 | 4 | namespace TodoList.Infrastructure.Persistence.Configurations; 5 | 6 | public class TodoListConfiguration : IEntityTypeConfiguration 7 | { 8 | public void Configure(EntityTypeBuilder builder) 9 | { 10 | builder.Ignore(e => e.DomainEvents); 11 | 12 | builder.Property(t => t.Title) 13 | .HasMaxLength(200) 14 | .IsRequired(); 15 | 16 | builder.OwnsOne(b => b.Colour); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/TodoList.Infrastructure/Persistence/Repositories/RepositoryBase.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using System.Linq.Expressions; 3 | using TodoList.Application.Common; 4 | using TodoList.Application.Common.Interfaces; 5 | 6 | namespace TodoList.Infrastructure.Persistence.Repositories; 7 | 8 | public class RepositoryBase : IRepository where T : class 9 | { 10 | private readonly TodoListDbContext _dbContext; 11 | 12 | public RepositoryBase(TodoListDbContext dbContext) => _dbContext = dbContext; 13 | 14 | public virtual ValueTask GetAsync(object key) => _dbContext.Set().FindAsync(key); 15 | 16 | public async Task AddAsync(T entity, CancellationToken cancellationToken = default) 17 | { 18 | await _dbContext.Set().AddAsync(entity, cancellationToken); 19 | await _dbContext.SaveChangesAsync(cancellationToken); 20 | 21 | return entity; 22 | } 23 | 24 | public async Task UpdateAsync(T entity, CancellationToken cancellationToken = default) 25 | { 26 | // 对于一般的更新而言,都是Attach到实体上的,只需要设置该实体的State为Modified就可以了 27 | _dbContext.Entry(entity).State = EntityState.Modified; 28 | await _dbContext.SaveChangesAsync(cancellationToken); 29 | } 30 | 31 | public async Task DeleteAsync(object key) 32 | { 33 | var entity = await GetAsync(key); 34 | if (entity is not null) 35 | { 36 | await DeleteAsync(entity); 37 | } 38 | } 39 | 40 | public async Task DeleteAsync(T entity, CancellationToken cancellationToken = default) 41 | { 42 | _dbContext.Set().Remove(entity); 43 | await _dbContext.SaveChangesAsync(cancellationToken); 44 | } 45 | 46 | public async Task DeleteRangeAsync(IEnumerable entities, CancellationToken cancellationToken = default) 47 | { 48 | _dbContext.Set().RemoveRange(entities); 49 | await _dbContext.SaveChangesAsync(cancellationToken); 50 | } 51 | 52 | // 1. 查询基础操作接口实现 53 | public IQueryable GetAsQueryable() 54 | => _dbContext.Set(); 55 | 56 | public IQueryable GetAsQueryable(ISpecification spec) 57 | => ApplySpecification(spec); 58 | public IQueryable GetAsQueryable(Expression> condition) 59 | => _dbContext.Set().Where(condition); 60 | 61 | // 2. 查询数量相关接口实现 62 | public int Count(Expression> condition) 63 | => _dbContext.Set().Count(condition); 64 | public int Count(ISpecification? spec = null) 65 | => null != spec ? ApplySpecification(spec).Count() : _dbContext.Set().Count(); 66 | public Task CountAsync(ISpecification? spec) 67 | => ApplySpecification(spec).CountAsync(); 68 | 69 | // 3. 查询存在性相关接口实现 70 | public bool Any(ISpecification? spec) 71 | => ApplySpecification(spec).Any(); 72 | public bool Any(Expression>? condition = null) 73 | => null != condition ? _dbContext.Set().Any(condition) : _dbContext.Set().Any(); 74 | 75 | // 4. 根据条件获取原始实体类型数据相关接口实现 76 | public async Task GetAsync(Expression> condition) 77 | => await _dbContext.Set().FirstOrDefaultAsync(condition); 78 | public async Task> GetAsync() 79 | => await _dbContext.Set().AsNoTracking().ToListAsync(); 80 | public async Task> GetAsync(ISpecification? spec) 81 | => await ApplySpecification(spec).AsNoTracking().ToListAsync(); 82 | 83 | // 5. 根据条件获取映射实体类型数据相关接口实现 84 | public TResult? SelectFirstOrDefault(ISpecification? spec, Expression> selector) 85 | => ApplySpecification(spec).AsNoTracking().Select(selector).FirstOrDefault(); 86 | public Task SelectFirstOrDefaultAsync(ISpecification? spec, Expression> selector) 87 | => ApplySpecification(spec).AsNoTracking().Select(selector).FirstOrDefaultAsync(); 88 | 89 | public async Task> SelectAsync(Expression> selector) 90 | => await _dbContext.Set().AsNoTracking().Select(selector).ToListAsync(); 91 | public async Task> SelectAsync(ISpecification? spec, Expression> selector) 92 | => await ApplySpecification(spec).AsNoTracking().Select(selector).ToListAsync(); 93 | public async Task> SelectAsync( 94 | Expression> groupExpression, 95 | Expression, TResult>> selector, 96 | ISpecification? spec = null) 97 | => null != spec ? 98 | await ApplySpecification(spec).AsNoTracking().GroupBy(groupExpression).Select(selector).ToListAsync() : 99 | await _dbContext.Set().AsNoTracking().GroupBy(groupExpression).Select(selector).ToListAsync(); 100 | 101 | public async Task SaveChangesAsync(CancellationToken cancellationToken = default) 102 | { 103 | await _dbContext.SaveChangesAsync(cancellationToken); 104 | } 105 | private IQueryable ApplySpecification(ISpecification? spec) 106 | => SpecificationEvaluator.GetQuery(_dbContext.Set().AsQueryable(), spec); 107 | } -------------------------------------------------------------------------------- /src/TodoList.Infrastructure/Persistence/TodoListDbContext.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using Microsoft.AspNetCore.Identity.EntityFrameworkCore; 3 | using Microsoft.EntityFrameworkCore; 4 | using TodoList.Application.Common.Interfaces; 5 | using TodoList.Domain.Base; 6 | using TodoList.Domain.Base.Interfaces; 7 | using TodoList.Domain.Entities; 8 | using TodoList.Infrastructure.Identity; 9 | 10 | namespace TodoList.Infrastructure.Persistence; 11 | public class TodoListDbContext : IdentityDbContext 12 | { 13 | private readonly IDomainEventService _domainEventService; 14 | private readonly ICurrentUserService _currentUserService; 15 | 16 | public TodoListDbContext( 17 | DbContextOptions options, 18 | IDomainEventService domainEventService, 19 | ICurrentUserService currentUserService) : base(options) 20 | { 21 | _domainEventService = domainEventService; 22 | _currentUserService = currentUserService; 23 | } 24 | 25 | public DbSet TodoLists => Set(); 26 | public DbSet TodoItems => Set(); 27 | 28 | public override async Task SaveChangesAsync(CancellationToken cancellationToken = new()) 29 | { 30 | // 在我们重写的SaveChangesAsync方法中,去设置审计相关的字段,目前对于修改人这个字段暂时先给个定值,等到后面讲到认证鉴权的时候再回过头来看这里 31 | foreach (var entry in ChangeTracker.Entries()) 32 | { 33 | switch (entry.State) 34 | { 35 | case EntityState.Added: 36 | entry.Entity.CreatedBy = _currentUserService.UserName; 37 | entry.Entity.Created = DateTime.UtcNow; 38 | break; 39 | 40 | case EntityState.Modified: 41 | entry.Entity.LastModifiedBy = _currentUserService.UserName; 42 | entry.Entity.LastModified = DateTime.UtcNow; 43 | break; 44 | } 45 | } 46 | 47 | // 在写数据库的时候同时发送领域事件,这里要注意一定要保证写入数据库成功后再发送领域事件,否则会导致领域对象状态的不一致问题。 48 | var events = ChangeTracker.Entries() 49 | .Select(x => x.Entity.DomainEvents) 50 | .SelectMany(x => x) 51 | .Where(domainEvent => !domainEvent.IsPublished) 52 | .ToArray(); 53 | 54 | var result = await base.SaveChangesAsync(cancellationToken); 55 | 56 | await DispatchEvents(events); 57 | 58 | return result; 59 | } 60 | 61 | protected override void OnModelCreating(ModelBuilder builder) 62 | { 63 | // 应用当前Assembly中定义的所有的Configurations,就不需要一个一个去写了。 64 | builder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly()); 65 | 66 | base.OnModelCreating(builder); 67 | } 68 | 69 | private async Task DispatchEvents(DomainEvent[] events) 70 | { 71 | foreach (var @event in events) 72 | { 73 | @event.IsPublished = true; 74 | await _domainEventService.Publish(@event); 75 | } 76 | } 77 | } -------------------------------------------------------------------------------- /src/TodoList.Infrastructure/Persistence/TodoListDbContextSeed.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Identity; 2 | using Microsoft.EntityFrameworkCore; 3 | using TodoList.Domain.Entities; 4 | using TodoList.Domain.Enums; 5 | using TodoList.Domain.ValueObjects; 6 | using TodoList.Infrastructure.Identity; 7 | 8 | namespace TodoList.Infrastructure.Persistence; 9 | 10 | public static class TodoListDbContextSeed 11 | { 12 | public static async Task SeedDefaultUserAsync(UserManager userManager, RoleManager roleManager) 13 | { 14 | var administratorRole = new IdentityRole("Administrator"); 15 | 16 | if (roleManager.Roles.All(r => r.Name != administratorRole.Name)) 17 | { 18 | await roleManager.CreateAsync(administratorRole); 19 | } 20 | 21 | var administrator = new ApplicationUser { UserName = "admin@localhost", Email = "admin@localhost" }; 22 | 23 | if (userManager.Users.All(u => u.UserName != administrator.UserName)) 24 | { 25 | // 创建的用户名为admin@localhost,密码是admin123,角色是Administrator 26 | await userManager.CreateAsync(administrator, "admin123"); 27 | await userManager.AddToRolesAsync(administrator, new[] { administratorRole.Name }); 28 | } 29 | } 30 | 31 | public static async Task SeedSampleDataAsync(TodoListDbContext context) 32 | { 33 | if (!context.TodoLists.Any()) 34 | { 35 | var list = new Domain.Entities.TodoList 36 | { 37 | Title = "Shopping", 38 | Colour = Colour.Blue 39 | }; 40 | list.Items.Add(new TodoItem { Title = "Apples", Done = true, Priority = PriorityLevel.High}); 41 | list.Items.Add(new TodoItem { Title = "Milk", Done = true }); 42 | list.Items.Add(new TodoItem { Title = "Bread", Done = true }); 43 | list.Items.Add(new TodoItem { Title = "Toilet paper" }); 44 | list.Items.Add(new TodoItem { Title = "Pasta" }); 45 | list.Items.Add(new TodoItem { Title = "Tissues" }); 46 | list.Items.Add(new TodoItem { Title = "Tuna" }); 47 | list.Items.Add(new TodoItem { Title = "Water" }); 48 | 49 | context.TodoLists.Add(list); 50 | 51 | await context.SaveChangesAsync(); 52 | } 53 | } 54 | 55 | public static async Task UpdateSampleDataAsync(TodoListDbContext context) 56 | { 57 | var sampleTodoList = await context.TodoLists.FirstOrDefaultAsync(); 58 | if (sampleTodoList == null) 59 | { 60 | return; 61 | } 62 | 63 | sampleTodoList.Title = "Shopping - modified"; 64 | 65 | // 演示更新时审计字段的变化 66 | context.Update(sampleTodoList); 67 | await context.SaveChangesAsync(); 68 | } 69 | } -------------------------------------------------------------------------------- /src/TodoList.Infrastructure/Services/DomainEventService.cs: -------------------------------------------------------------------------------- 1 | using MediatR; 2 | using Microsoft.Extensions.Logging; 3 | using TodoList.Application.Common.Interfaces; 4 | using TodoList.Application.Common.Models; 5 | using TodoList.Domain.Base; 6 | 7 | namespace TodoList.Infrastructure.Services; 8 | 9 | public class DomainEventService : IDomainEventService 10 | { 11 | private readonly IMediator _mediator; 12 | private readonly ILogger _logger; 13 | 14 | public DomainEventService(IMediator mediator, ILogger logger) 15 | { 16 | _mediator = mediator; 17 | _logger = logger; 18 | } 19 | 20 | public async Task Publish(DomainEvent domainEvent) 21 | { 22 | _logger.LogInformation("Publishing domain event. Event - {event}", domainEvent.GetType().Name); 23 | await _mediator.Publish(GetNotificationCorrespondingToDomainEvent(domainEvent)); 24 | } 25 | 26 | private INotification GetNotificationCorrespondingToDomainEvent(DomainEvent domainEvent) 27 | { 28 | return (INotification)Activator.CreateInstance(typeof(DomainEventNotification<>).MakeGenericType(domainEvent.GetType()), domainEvent)!; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/TodoList.Infrastructure/TodoList.Infrastructure.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | net6.0 19 | enable 20 | enable 21 | 22 | 23 | 24 | --------------------------------------------------------------------------------