├── .gitattributes ├── .gitignore ├── .idea └── .idea.BlazorMinimalApis │ └── .idea │ ├── .name │ ├── encodings.xml │ ├── indexLayout.xml │ ├── projectSettingsUpdater.xml │ ├── vcs.xml │ └── workspace.xml ├── BlazorMinimalApis.sln ├── BlazorMinimalApis ├── BlazorMinimalApis.csproj └── Lib │ ├── Helpers │ └── ObjectExtensions.cs │ ├── Routing │ ├── ApiController.cs │ ├── XController.cs │ ├── XHandler.cs │ └── XPage.cs │ ├── Session │ └── SessionManager.cs │ ├── Validation │ └── ValidationError.cs │ └── Views │ ├── EmptyLayout.razor │ ├── PageComponent.razor │ ├── PageState.cs │ ├── XComponent.cs │ └── XLayout.razor ├── README.md ├── Samples ├── BlazorMinimalApi.Pages │ ├── BlazorMinimalApis.Pages.csproj │ ├── Data │ │ └── Database.cs │ ├── Lib │ │ ├── IRouteDefinition.cs │ │ └── RegisterRoutesExtension.cs │ ├── Pages │ │ ├── Api │ │ │ └── Contacts │ │ │ │ └── ListContacts.cs │ │ ├── Contacts │ │ │ ├── CreateContact.cs │ │ │ ├── DeleteContact.cs │ │ │ ├── EditContact.cs │ │ │ ├── ListContacts.cs │ │ │ ├── _CreateContact.razor │ │ │ ├── _EditContact.razor │ │ │ ├── _ListContacts.razor │ │ │ └── _SearchContacts.razor │ │ ├── Home │ │ │ ├── Home.cs │ │ │ ├── _Home.razor │ │ │ └── _RandomNumber.razor │ │ ├── Shared │ │ │ ├── FlashMessages.razor │ │ │ └── Layout │ │ │ │ └── MainLayout.razor │ │ └── _Imports.razor │ ├── Program.cs │ ├── Properties │ │ └── launchSettings.json │ ├── Routes │ │ ├── Api.cs │ │ └── Web.cs │ ├── appsettings.json │ └── wwwroot │ │ ├── app.css │ │ └── favicon.png ├── BlazorMinimalApi.Slices │ ├── Applications │ │ ├── Common │ │ │ ├── Components │ │ │ │ └── FlashMessages.razor │ │ │ └── Layouts │ │ │ │ └── MainLayout.razor │ │ ├── Contacts │ │ │ ├── Handlers │ │ │ │ ├── CreateContact.cs │ │ │ │ ├── DeleteContact.cs │ │ │ │ ├── EditContact.cs │ │ │ │ ├── ListContacts.cs │ │ │ │ ├── ListContactsApi.cs │ │ │ │ └── SearchContacts.cs │ │ │ ├── Mappers │ │ │ │ └── ContactMapper.cs │ │ │ ├── Models │ │ │ │ ├── CreateContactForm.cs │ │ │ │ └── EditContactForm.cs │ │ │ ├── Routes.cs │ │ │ └── Views │ │ │ │ ├── ContactsTable.razor │ │ │ │ ├── Create.razor │ │ │ │ ├── Edit.razor │ │ │ │ ├── List.razor │ │ │ │ └── _Imports.razor │ │ ├── Home │ │ │ ├── Handlers │ │ │ │ └── ShowHome.cs │ │ │ ├── Routes.cs │ │ │ └── Views │ │ │ │ ├── Show.razor │ │ │ │ └── _RandomNumber.razor │ │ └── _Imports.razor │ ├── BlazorMinimalApi.Slices.csproj │ ├── Data │ │ └── Database.cs │ ├── Lib │ │ ├── IRouteDefinition.cs │ │ └── RegisterRoutesExtension.cs │ ├── Program.cs │ ├── Properties │ │ └── launchSettings.json │ ├── appsettings.json │ └── wwwroot │ │ ├── app.css │ │ └── favicon.png └── BlazorMinimalApis.Mvc │ ├── BlazorMinimalApis.Mvc.csproj │ ├── Controllers │ ├── Api │ │ └── ContactApiController.cs │ ├── ContactController.cs │ └── HomeController.cs │ ├── Data │ └── Database.cs │ ├── Lib │ ├── IRouteDefinition.cs │ └── RegisterRoutesExtension.cs │ ├── Program.cs │ ├── Properties │ └── launchSettings.json │ ├── Routes │ ├── Api.cs │ └── Web.cs │ ├── Views │ ├── Components │ │ └── FlashMessages.razor │ ├── Contacts │ │ ├── Create.razor │ │ ├── Edit.razor │ │ ├── List.razor │ │ └── _ContactsTable.razor │ ├── Home │ │ ├── Home.razor │ │ └── _RandomNumber.razor │ ├── Layouts │ │ └── MainLayout.razor │ └── _Imports.razor │ ├── appsettings.Development.json │ ├── appsettings.json │ └── wwwroot │ ├── app.css │ ├── bootstrap │ ├── bootstrap.min.css │ └── bootstrap.min.css.map │ └── favicon.png └── global.json /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Oo]ut/ 33 | [Ll]og/ 34 | [Ll]ogs/ 35 | 36 | # Visual Studio 2015/2017 cache/options directory 37 | .vs/ 38 | # Uncomment if you have tasks that create the project's static files in wwwroot 39 | #wwwroot/ 40 | 41 | # Visual Studio 2017 auto generated files 42 | Generated\ Files/ 43 | 44 | # MSTest test Results 45 | [Tt]est[Rr]esult*/ 46 | [Bb]uild[Ll]og.* 47 | 48 | # NUnit 49 | *.VisualState.xml 50 | TestResult.xml 51 | nunit-*.xml 52 | 53 | # Build Results of an ATL Project 54 | [Dd]ebugPS/ 55 | [Rr]eleasePS/ 56 | dlldata.c 57 | 58 | # Benchmark Results 59 | BenchmarkDotNet.Artifacts/ 60 | 61 | # .NET Core 62 | project.lock.json 63 | project.fragment.lock.json 64 | artifacts/ 65 | 66 | # ASP.NET Scaffolding 67 | ScaffoldingReadMe.txt 68 | 69 | # StyleCop 70 | StyleCopReport.xml 71 | 72 | # Files built by Visual Studio 73 | *_i.c 74 | *_p.c 75 | *_h.h 76 | *.ilk 77 | *.meta 78 | *.obj 79 | *.iobj 80 | *.pch 81 | *.pdb 82 | *.ipdb 83 | *.pgc 84 | *.pgd 85 | *.rsp 86 | *.sbr 87 | *.tlb 88 | *.tli 89 | *.tlh 90 | *.tmp 91 | *.tmp_proj 92 | *_wpftmp.csproj 93 | *.log 94 | *.vspscc 95 | *.vssscc 96 | .builds 97 | *.pidb 98 | *.svclog 99 | *.scc 100 | 101 | # Chutzpah Test files 102 | _Chutzpah* 103 | 104 | # Visual C++ cache files 105 | ipch/ 106 | *.aps 107 | *.ncb 108 | *.opendb 109 | *.opensdf 110 | *.sdf 111 | *.cachefile 112 | *.VC.db 113 | *.VC.VC.opendb 114 | 115 | # Visual Studio profiler 116 | *.psess 117 | *.vsp 118 | *.vspx 119 | *.sap 120 | 121 | # Visual Studio Trace Files 122 | *.e2e 123 | 124 | # TFS 2012 Local Workspace 125 | $tf/ 126 | 127 | # Guidance Automation Toolkit 128 | *.gpState 129 | 130 | # ReSharper is a .NET coding add-in 131 | _ReSharper*/ 132 | *.[Rr]e[Ss]harper 133 | *.DotSettings.user 134 | 135 | # TeamCity is a build add-in 136 | _TeamCity* 137 | 138 | # DotCover is a Code Coverage Tool 139 | *.dotCover 140 | 141 | # AxoCover is a Code Coverage Tool 142 | .axoCover/* 143 | !.axoCover/settings.json 144 | 145 | # Coverlet is a free, cross platform Code Coverage Tool 146 | coverage*.json 147 | coverage*.xml 148 | coverage*.info 149 | 150 | # Visual Studio code coverage results 151 | *.coverage 152 | *.coveragexml 153 | 154 | # NCrunch 155 | _NCrunch_* 156 | .*crunch*.local.xml 157 | nCrunchTemp_* 158 | 159 | # MightyMoose 160 | *.mm.* 161 | AutoTest.Net/ 162 | 163 | # Web workbench (sass) 164 | .sass-cache/ 165 | 166 | # Installshield output folder 167 | [Ee]xpress/ 168 | 169 | # DocProject is a documentation generator add-in 170 | DocProject/buildhelp/ 171 | DocProject/Help/*.HxT 172 | DocProject/Help/*.HxC 173 | DocProject/Help/*.hhc 174 | DocProject/Help/*.hhk 175 | DocProject/Help/*.hhp 176 | DocProject/Help/Html2 177 | DocProject/Help/html 178 | 179 | # Click-Once directory 180 | publish/ 181 | 182 | # Publish Web Output 183 | *.[Pp]ublish.xml 184 | *.azurePubxml 185 | # Note: Comment the next line if you want to checkin your web deploy settings, 186 | # but database connection strings (with potential passwords) will be unencrypted 187 | *.pubxml 188 | *.publishproj 189 | 190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 191 | # checkin your Azure Web App publish settings, but sensitive information contained 192 | # in these scripts will be unencrypted 193 | PublishScripts/ 194 | 195 | # NuGet Packages 196 | *.nupkg 197 | # NuGet Symbol Packages 198 | *.snupkg 199 | # The packages folder can be ignored because of Package Restore 200 | **/[Pp]ackages/* 201 | # except build/, which is used as an MSBuild target. 202 | !**/[Pp]ackages/build/ 203 | # Uncomment if necessary however generally it will be regenerated when needed 204 | #!**/[Pp]ackages/repositories.config 205 | # NuGet v3's project.json files produces more ignorable files 206 | *.nuget.props 207 | *.nuget.targets 208 | 209 | # Microsoft Azure Build Output 210 | csx/ 211 | *.build.csdef 212 | 213 | # Microsoft Azure Emulator 214 | ecf/ 215 | rcf/ 216 | 217 | # Windows Store app package directories and files 218 | AppPackages/ 219 | BundleArtifacts/ 220 | Package.StoreAssociation.xml 221 | _pkginfo.txt 222 | *.appx 223 | *.appxbundle 224 | *.appxupload 225 | 226 | # Visual Studio cache files 227 | # files ending in .cache can be ignored 228 | *.[Cc]ache 229 | # but keep track of directories ending in .cache 230 | !?*.[Cc]ache/ 231 | 232 | # Others 233 | ClientBin/ 234 | ~$* 235 | *~ 236 | *.dbmdl 237 | *.dbproj.schemaview 238 | *.jfm 239 | *.pfx 240 | *.publishsettings 241 | orleans.codegen.cs 242 | 243 | # Including strong name files can present a security risk 244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 245 | #*.snk 246 | 247 | # Since there are multiple workflows, uncomment next line to ignore bower_components 248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 249 | #bower_components/ 250 | 251 | # RIA/Silverlight projects 252 | Generated_Code/ 253 | 254 | # Backup & report files from converting an old project file 255 | # to a newer Visual Studio version. Backup files are not needed, 256 | # because we have git ;-) 257 | _UpgradeReport_Files/ 258 | Backup*/ 259 | UpgradeLog*.XML 260 | UpgradeLog*.htm 261 | ServiceFabricBackup/ 262 | *.rptproj.bak 263 | 264 | # SQL Server files 265 | *.mdf 266 | *.ldf 267 | *.ndf 268 | 269 | # Business Intelligence projects 270 | *.rdl.data 271 | *.bim.layout 272 | *.bim_*.settings 273 | *.rptproj.rsuser 274 | *- [Bb]ackup.rdl 275 | *- [Bb]ackup ([0-9]).rdl 276 | *- [Bb]ackup ([0-9][0-9]).rdl 277 | 278 | # Microsoft Fakes 279 | FakesAssemblies/ 280 | 281 | # GhostDoc plugin setting file 282 | *.GhostDoc.xml 283 | 284 | # Node.js Tools for Visual Studio 285 | .ntvs_analysis.dat 286 | node_modules/ 287 | 288 | # Visual Studio 6 build log 289 | *.plg 290 | 291 | # Visual Studio 6 workspace options file 292 | *.opt 293 | 294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 295 | *.vbw 296 | 297 | # Visual Studio LightSwitch build output 298 | **/*.HTMLClient/GeneratedArtifacts 299 | **/*.DesktopClient/GeneratedArtifacts 300 | **/*.DesktopClient/ModelManifest.xml 301 | **/*.Server/GeneratedArtifacts 302 | **/*.Server/ModelManifest.xml 303 | _Pvt_Extensions 304 | 305 | # Paket dependency manager 306 | .paket/paket.exe 307 | paket-files/ 308 | 309 | # FAKE - F# Make 310 | .fake/ 311 | 312 | # CodeRush personal settings 313 | .cr/personal 314 | 315 | # Python Tools for Visual Studio (PTVS) 316 | __pycache__/ 317 | *.pyc 318 | 319 | # Cake - Uncomment if you are using it 320 | # tools/** 321 | # !tools/packages.config 322 | 323 | # Tabs Studio 324 | *.tss 325 | 326 | # Telerik's JustMock configuration file 327 | *.jmconfig 328 | 329 | # BizTalk build output 330 | *.btp.cs 331 | *.btm.cs 332 | *.odx.cs 333 | *.xsd.cs 334 | 335 | # OpenCover UI analysis results 336 | OpenCover/ 337 | 338 | # Azure Stream Analytics local run output 339 | ASALocalRun/ 340 | 341 | # MSBuild Binary and Structured Log 342 | *.binlog 343 | 344 | # NVidia Nsight GPU debugger configuration file 345 | *.nvuser 346 | 347 | # MFractors (Xamarin productivity tool) working folder 348 | .mfractor/ 349 | 350 | # Local History for Visual Studio 351 | .localhistory/ 352 | 353 | # BeatPulse healthcheck temp database 354 | healthchecksdb 355 | 356 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 357 | MigrationBackup/ 358 | 359 | # Ionide (cross platform F# VS Code tools) working folder 360 | .ionide/ 361 | 362 | # Fody - auto-generated XML schema 363 | FodyWeavers.xsd -------------------------------------------------------------------------------- /.idea/.idea.BlazorMinimalApis/.idea/.name: -------------------------------------------------------------------------------- 1 | BlazorMinimalApis -------------------------------------------------------------------------------- /.idea/.idea.BlazorMinimalApis/.idea/encodings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /.idea/.idea.BlazorMinimalApis/.idea/indexLayout.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /.idea/.idea.BlazorMinimalApis/.idea/projectSettingsUpdater.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 6 | -------------------------------------------------------------------------------- /.idea/.idea.BlazorMinimalApis/.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.idea/.idea.BlazorMinimalApis/.idea/workspace.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Samples/BlazorMinimalApi.Endpoints/BlazorMinimalApis.Endpoints.csproj 5 | Samples/BlazorMinimalApi.Endpoints/BlazorMinimalApis.Endpoints.csproj 6 | Samples/BlazorMinimalApi.Endpoints/BlazorMinimalApis.Endpoints.csproj 7 | Samples/BlazorMinimalApi.Pages/BlazorMinimalApis.Pages.csproj 8 | Samples/BlazorMinimalApi.Pages/BlazorMinimalApis.Pages.csproj 9 | Samples/BlazorMinimalApi.Pages/BlazorMinimalApis.Pages.csproj 10 | Samples/BlazorMinimalApis.Mvc/BlazorMinimalApis.Mvc.csproj 11 | Samples/BlazorMinimalApis.Mvc/BlazorMinimalApis.Mvc.csproj 12 | Samples/BlazorMinimalApis.Mvc/BlazorMinimalApis.Mvc.csproj 13 | 14 | 15 | 17 | 18 | 19 | 20 | 21 | 26 | 27 | 29 | { 30 | "associatedIndex": 8 31 | } 32 | 33 | 34 | 35 | 36 | 37 | 40 | { 41 | "keyToString": { 42 | "RunOnceActivity.OpenProjectViewOnStart": "true", 43 | "RunOnceActivity.ShowReadmeOnStart": "true", 44 | "WebServerToolWindowFactoryState": "false", 45 | "git-widget-placeholder": "master", 46 | "node.js.detected.package.eslint": "true", 47 | "node.js.detected.package.tslint": "true", 48 | "node.js.selected.package.eslint": "(autodetect)", 49 | "node.js.selected.package.tslint": "(autodetect)", 50 | "vue.rearranger.settings.migration": "true" 51 | }, 52 | "keyToStringList": { 53 | "rider.external.source.directories": [ 54 | "C:\\Users\\Weston\\AppData\\Roaming\\JetBrains\\Rider2023.2\\resharper-host\\DecompilerCache", 55 | "C:\\Users\\Weston\\AppData\\Roaming\\JetBrains\\Rider2023.2\\resharper-host\\SourcesCache", 56 | "C:\\Users\\Weston\\AppData\\Local\\Symbols\\src" 57 | ] 58 | } 59 | } 60 | 61 | 62 | 76 | 77 | 91 | 92 | 106 | 107 | 121 | 122 | 136 | 137 | 151 | 152 | 166 | 167 | 181 | 182 | 196 | 197 | 198 | 199 | 200 | 201 | 1696010039176 202 | 212 | 213 | 214 | 215 | 217 | 218 | 220 | -------------------------------------------------------------------------------- /BlazorMinimalApis.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.8.34112.27 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BlazorMinimalApis.Pages", "Samples\BlazorMinimalApi.Pages\BlazorMinimalApis.Pages.csproj", "{4A709DBC-7C6D-418D-86D4-19098947B792}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BlazorMinimalApis", "BlazorMinimalApis\BlazorMinimalApis.csproj", "{76133159-61DF-409C-AF01-16D3F94A4CED}" 9 | EndProject 10 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BlazorMinimalApis.Mvc", "Samples\BlazorMinimalApis.Mvc\BlazorMinimalApis.Mvc.csproj", "{A08B95A6-185E-4FAE-8A80-0FAE8ABB3BC0}" 11 | EndProject 12 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BlazorMinimalApi.Slices", "Samples\BlazorMinimalApi.Slices\BlazorMinimalApi.Slices.csproj", "{5EF32691-BD61-47A6-AF8F-61A91B743016}" 13 | EndProject 14 | Global 15 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 16 | Debug|Any CPU = Debug|Any CPU 17 | Release|Any CPU = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 20 | {4A709DBC-7C6D-418D-86D4-19098947B792}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {4A709DBC-7C6D-418D-86D4-19098947B792}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {4A709DBC-7C6D-418D-86D4-19098947B792}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {4A709DBC-7C6D-418D-86D4-19098947B792}.Release|Any CPU.Build.0 = Release|Any CPU 24 | {76133159-61DF-409C-AF01-16D3F94A4CED}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 25 | {76133159-61DF-409C-AF01-16D3F94A4CED}.Debug|Any CPU.Build.0 = Debug|Any CPU 26 | {76133159-61DF-409C-AF01-16D3F94A4CED}.Release|Any CPU.ActiveCfg = Release|Any CPU 27 | {76133159-61DF-409C-AF01-16D3F94A4CED}.Release|Any CPU.Build.0 = Release|Any CPU 28 | {A08B95A6-185E-4FAE-8A80-0FAE8ABB3BC0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 29 | {A08B95A6-185E-4FAE-8A80-0FAE8ABB3BC0}.Debug|Any CPU.Build.0 = Debug|Any CPU 30 | {A08B95A6-185E-4FAE-8A80-0FAE8ABB3BC0}.Release|Any CPU.ActiveCfg = Release|Any CPU 31 | {A08B95A6-185E-4FAE-8A80-0FAE8ABB3BC0}.Release|Any CPU.Build.0 = Release|Any CPU 32 | {5EF32691-BD61-47A6-AF8F-61A91B743016}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 33 | {5EF32691-BD61-47A6-AF8F-61A91B743016}.Debug|Any CPU.Build.0 = Debug|Any CPU 34 | {5EF32691-BD61-47A6-AF8F-61A91B743016}.Release|Any CPU.ActiveCfg = Release|Any CPU 35 | {5EF32691-BD61-47A6-AF8F-61A91B743016}.Release|Any CPU.Build.0 = Release|Any CPU 36 | EndGlobalSection 37 | GlobalSection(SolutionProperties) = preSolution 38 | HideSolutionNode = FALSE 39 | EndGlobalSection 40 | GlobalSection(ExtensibilityGlobals) = postSolution 41 | SolutionGuid = {9652008F-A9D9-42B7-88E4-B51AECF57811} 42 | EndGlobalSection 43 | EndGlobal 44 | -------------------------------------------------------------------------------- /BlazorMinimalApis/BlazorMinimalApis.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net8.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /BlazorMinimalApis/Lib/Helpers/ObjectExtensions.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel; 2 | 3 | namespace BlazorMinimalApis.Lib.Helpers; 4 | 5 | public static class ObjectExtensions 6 | { 7 | public static Dictionary ToDictionary(this object values) 8 | { 9 | var dict = new Dictionary(StringComparer.OrdinalIgnoreCase); 10 | 11 | if (values != null) 12 | { 13 | foreach (PropertyDescriptor propertyDescriptor in TypeDescriptor.GetProperties(values)) 14 | { 15 | object obj = propertyDescriptor.GetValue(values); 16 | dict.Add(propertyDescriptor.Name, obj); 17 | } 18 | } 19 | 20 | return dict; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /BlazorMinimalApis/Lib/Routing/ApiController.cs: -------------------------------------------------------------------------------- 1 | using BlazorMinimalApis.Lib.Views; 2 | using BlazorMinimalApis.Lib.Helpers; 3 | using BlazorMinimalApis.Lib.Validation; 4 | using FluentValidation; 5 | using Microsoft.AspNetCore.Components.Endpoints; 6 | using System.ComponentModel.DataAnnotations; 7 | using Microsoft.AspNetCore.Http; 8 | 9 | namespace BlazorMinimalApis.Lib.Routing; 10 | 11 | public abstract class ApiController 12 | { 13 | public ValidationResponse Validation = new(); 14 | 15 | public ValidationResponse Validate(TData data) 16 | { 17 | var ctx = new ValidationContext(data); 18 | var results = new List(); 19 | ValidationResponse validationResponse = new(); 20 | if (!Validator.TryValidateObject(data, ctx, results, true)) 21 | { 22 | validationResponse.HasErrors = true; 23 | foreach (var error in results) 24 | { 25 | var ve = new ValidationError() 26 | { 27 | Message = error.ErrorMessage, 28 | MemberName = error.MemberNames.First(), 29 | }; 30 | validationResponse.Errors.Add(ve); 31 | } 32 | } 33 | else 34 | { 35 | validationResponse.HasErrors = false; 36 | } 37 | Validation = validationResponse; 38 | return validationResponse; 39 | } 40 | 41 | public ValidationResponse Validate(TData data, AbstractValidator validator) 42 | { 43 | ValidationResponse validationResponse = new(); 44 | FluentValidation.Results.ValidationResult results = validator.Validate(data); 45 | 46 | if (!results.IsValid) 47 | { 48 | validationResponse.HasErrors = true; 49 | foreach (var error in results.Errors) 50 | { 51 | var ve = new ValidationError() 52 | { 53 | Message = error.ErrorMessage, 54 | MemberName = error.PropertyName 55 | }; 56 | validationResponse.Errors.Add(ve); 57 | } 58 | } 59 | else 60 | { 61 | validationResponse.HasErrors = false; 62 | } 63 | Validation = validationResponse; 64 | return validationResponse; 65 | } 66 | 67 | public ValidationResponse GetErrors() 68 | { 69 | return Validation; 70 | } 71 | 72 | public void AddError(string key, string message) 73 | { 74 | Validation.HasErrors = true; 75 | Validation.Errors.Add(new ValidationError() { MemberName = key, Message = message }); 76 | } 77 | 78 | public IResult Redirect(string url) 79 | { 80 | return Results.Redirect(url); 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /BlazorMinimalApis/Lib/Routing/XController.cs: -------------------------------------------------------------------------------- 1 | using BlazorMinimalApis.Lib.Views; 2 | using BlazorMinimalApis.Lib.Helpers; 3 | using BlazorMinimalApis.Lib.Validation; 4 | using FluentValidation; 5 | using System.ComponentModel.DataAnnotations; 6 | using Microsoft.AspNetCore.Http; 7 | using Microsoft.AspNetCore.Http.HttpResults; 8 | 9 | namespace BlazorMinimalApis.Lib.Routing; 10 | 11 | public abstract class XController 12 | { 13 | public ValidationResponse Validation = new(); 14 | 15 | public IResult View(object data) 16 | { 17 | var componentData = data.ToDictionary(); 18 | var errors = new List(); 19 | if (Validation.HasErrors && Validation.Errors.Count > 0) 20 | { 21 | errors = Validation.Errors; 22 | } 23 | var componentType = typeof(TComponent); 24 | return new RazorComponentResult(typeof(PageComponent), new { ComponentType = componentType, ComponentParameters = componentData, Errors = errors }); 25 | } 26 | 27 | public IResult View() 28 | { 29 | return View(new { }); 30 | } 31 | 32 | public ValidationResponse Validate(TData data) 33 | { 34 | var ctx = new ValidationContext(data); 35 | var results = new List(); 36 | ValidationResponse validationResponse = new(); 37 | if (!Validator.TryValidateObject(data, ctx, results, true)) 38 | { 39 | validationResponse.HasErrors = true; 40 | foreach (var error in results) 41 | { 42 | var ve = new ValidationError() 43 | { 44 | Message = error.ErrorMessage, 45 | MemberName = error.MemberNames.First(), 46 | }; 47 | validationResponse.Errors.Add(ve); 48 | } 49 | } 50 | else 51 | { 52 | validationResponse.HasErrors = false; 53 | } 54 | Validation = validationResponse; 55 | return validationResponse; 56 | } 57 | 58 | public ValidationResponse Validate(TData data, TValidator validator) where TValidator : AbstractValidator 59 | { 60 | ValidationResponse validationResponse = new(); 61 | FluentValidation.Results.ValidationResult results = validator.Validate(data); 62 | 63 | if (!results.IsValid) 64 | { 65 | validationResponse.HasErrors = true; 66 | foreach (var error in results.Errors) 67 | { 68 | var ve = new ValidationError() 69 | { 70 | Message = error.ErrorMessage, 71 | MemberName = error.PropertyName 72 | }; 73 | validationResponse.Errors.Add(ve); 74 | } 75 | } 76 | else 77 | { 78 | validationResponse.HasErrors = false; 79 | } 80 | Validation = validationResponse; 81 | return validationResponse; 82 | } 83 | 84 | public async Task ValidateAsync(TData data, TValidator validator) where TValidator : AbstractValidator 85 | { 86 | ValidationResponse validationResponse = new(); 87 | FluentValidation.Results.ValidationResult results = await validator.ValidateAsync(data); 88 | 89 | if (!results.IsValid) 90 | { 91 | validationResponse.HasErrors = true; 92 | foreach (var error in results.Errors) 93 | { 94 | var ve = new ValidationError() 95 | { 96 | Message = error.ErrorMessage, 97 | MemberName = error.PropertyName 98 | }; 99 | validationResponse.Errors.Add(ve); 100 | } 101 | } 102 | else 103 | { 104 | validationResponse.HasErrors = false; 105 | } 106 | Validation = validationResponse; 107 | return validationResponse; 108 | } 109 | 110 | public ValidationResponse GetErrors() 111 | { 112 | return Validation; 113 | } 114 | 115 | public void AddError(string key, string message) 116 | { 117 | Validation.HasErrors = true; 118 | Validation.Errors.Add(new ValidationError() { MemberName = key, Message = message }); 119 | } 120 | 121 | public IResult Redirect(string url) 122 | { 123 | return Results.Redirect(url); 124 | } 125 | 126 | public XController Flash(string key, string message) 127 | { 128 | return this; 129 | } 130 | } 131 | -------------------------------------------------------------------------------- /BlazorMinimalApis/Lib/Routing/XHandler.cs: -------------------------------------------------------------------------------- 1 | using BlazorMinimalApis.Lib.Helpers; 2 | using BlazorMinimalApis.Lib.Validation; 3 | using BlazorMinimalApis.Lib.Views; 4 | using FluentValidation; 5 | using Microsoft.AspNetCore.Http.HttpResults; 6 | using Microsoft.AspNetCore.Http; 7 | using System.ComponentModel.DataAnnotations; 8 | using Microsoft.AspNetCore.Builder; 9 | 10 | namespace BlazorMinimalApis.Lib.Routing; 11 | 12 | public abstract class XHandler 13 | { 14 | public ValidationResponse Validation = new(); 15 | 16 | public IResult View(object data) 17 | { 18 | var componentData = data.ToDictionary(); 19 | var errors = new List(); 20 | if (Validation.HasErrors && Validation.Errors.Count > 0) 21 | { 22 | errors = Validation.Errors; 23 | } 24 | var componentType = typeof(TComponent); 25 | return new RazorComponentResult(typeof(PageComponent), new { ComponentType = componentType, ComponentParameters = componentData, Errors = errors }); 26 | } 27 | 28 | public IResult View() 29 | { 30 | return View(new { }); 31 | } 32 | 33 | public ValidationResponse Validate(TData data) 34 | { 35 | var ctx = new ValidationContext(data); 36 | var results = new List(); 37 | ValidationResponse validationResponse = new(); 38 | if (!Validator.TryValidateObject(data, ctx, results, true)) 39 | { 40 | validationResponse.HasErrors = true; 41 | foreach (var error in results) 42 | { 43 | var ve = new ValidationError() 44 | { 45 | Message = error.ErrorMessage, 46 | MemberName = error.MemberNames.First(), 47 | }; 48 | validationResponse.Errors.Add(ve); 49 | } 50 | } 51 | else 52 | { 53 | validationResponse.HasErrors = false; 54 | } 55 | Validation = validationResponse; 56 | return validationResponse; 57 | } 58 | 59 | public ValidationResponse Validate(TData data, TValidator validator) where TValidator : AbstractValidator 60 | { 61 | ValidationResponse validationResponse = new(); 62 | FluentValidation.Results.ValidationResult results = validator.Validate(data); 63 | 64 | if (!results.IsValid) 65 | { 66 | validationResponse.HasErrors = true; 67 | foreach (var error in results.Errors) 68 | { 69 | var ve = new ValidationError() 70 | { 71 | Message = error.ErrorMessage, 72 | MemberName = error.PropertyName 73 | }; 74 | validationResponse.Errors.Add(ve); 75 | } 76 | } 77 | else 78 | { 79 | validationResponse.HasErrors = false; 80 | } 81 | Validation = validationResponse; 82 | return validationResponse; 83 | } 84 | 85 | public async Task ValidateAsync(TData data, TValidator validator) where TValidator : AbstractValidator 86 | { 87 | ValidationResponse validationResponse = new(); 88 | FluentValidation.Results.ValidationResult results = await validator.ValidateAsync(data); 89 | 90 | if (!results.IsValid) 91 | { 92 | validationResponse.HasErrors = true; 93 | foreach (var error in results.Errors) 94 | { 95 | var ve = new ValidationError() 96 | { 97 | Message = error.ErrorMessage, 98 | MemberName = error.PropertyName 99 | }; 100 | validationResponse.Errors.Add(ve); 101 | } 102 | } 103 | else 104 | { 105 | validationResponse.HasErrors = false; 106 | } 107 | Validation = validationResponse; 108 | return validationResponse; 109 | } 110 | 111 | public ValidationResponse GetErrors() 112 | { 113 | return Validation; 114 | } 115 | 116 | public void AddError(string key, string message) 117 | { 118 | Validation.HasErrors = true; 119 | Validation.Errors.Add(new ValidationError() { MemberName = key, Message = message }); 120 | } 121 | 122 | public IResult Redirect(string url) 123 | { 124 | return Results.Redirect(url); 125 | } 126 | } 127 | 128 | -------------------------------------------------------------------------------- /BlazorMinimalApis/Lib/Routing/XPage.cs: -------------------------------------------------------------------------------- 1 | using BlazorMinimalApis.Lib.Helpers; 2 | using BlazorMinimalApis.Lib.Validation; 3 | using BlazorMinimalApis.Lib.Views; 4 | using FluentValidation; 5 | using Microsoft.AspNetCore.Http.HttpResults; 6 | using Microsoft.AspNetCore.Http; 7 | using System.ComponentModel.DataAnnotations; 8 | using Microsoft.AspNetCore.Builder; 9 | 10 | namespace BlazorMinimalApis.Lib.Routing; 11 | 12 | public abstract class XPage 13 | { 14 | public ValidationResponse Validation = new(); 15 | 16 | public IResult Page() 17 | { 18 | var data = new { Model = this }; 19 | var componentData = data.ToDictionary(); 20 | var errors = new List(); 21 | if (Validation.HasErrors && Validation.Errors.Count > 0) 22 | { 23 | errors = Validation.Errors; 24 | } 25 | var componentType = typeof(TComponent); 26 | return new RazorComponentResult(typeof(PageComponent), new { ComponentType = componentType, ComponentParameters = componentData, Errors = errors }); 27 | } 28 | 29 | public IResult Page(object data) 30 | { 31 | var componentData = data.ToDictionary(); 32 | var errors = new List(); 33 | if (Validation.HasErrors && Validation.Errors.Count > 0) 34 | { 35 | errors = Validation.Errors; 36 | } 37 | var componentType = typeof(TComponent); 38 | return new RazorComponentResult(typeof(PageComponent), new { ComponentType = componentType, ComponentParameters = componentData, Errors = errors }); 39 | } 40 | 41 | public ValidationResponse Validate(TData data) 42 | { 43 | var ctx = new ValidationContext(data); 44 | var results = new List(); 45 | ValidationResponse validationResponse = new(); 46 | if (!Validator.TryValidateObject(data, ctx, results, true)) 47 | { 48 | validationResponse.HasErrors = true; 49 | foreach (var error in results) 50 | { 51 | var ve = new ValidationError() 52 | { 53 | Message = error.ErrorMessage, 54 | MemberName = error.MemberNames.First(), 55 | }; 56 | validationResponse.Errors.Add(ve); 57 | } 58 | } 59 | else 60 | { 61 | validationResponse.HasErrors = false; 62 | } 63 | Validation = validationResponse; 64 | return validationResponse; 65 | } 66 | 67 | public ValidationResponse Validate(TData data, TValidator validator) where TValidator : AbstractValidator 68 | { 69 | ValidationResponse validationResponse = new(); 70 | FluentValidation.Results.ValidationResult results = validator.Validate(data); 71 | 72 | if (!results.IsValid) 73 | { 74 | validationResponse.HasErrors = true; 75 | foreach (var error in results.Errors) 76 | { 77 | var ve = new ValidationError() 78 | { 79 | Message = error.ErrorMessage, 80 | MemberName = error.PropertyName 81 | }; 82 | validationResponse.Errors.Add(ve); 83 | } 84 | } 85 | else 86 | { 87 | validationResponse.HasErrors = false; 88 | } 89 | Validation = validationResponse; 90 | return validationResponse; 91 | } 92 | 93 | public async Task ValidateAsync(TData data, TValidator validator) where TValidator : AbstractValidator 94 | { 95 | ValidationResponse validationResponse = new(); 96 | FluentValidation.Results.ValidationResult results = await validator.ValidateAsync(data); 97 | 98 | if (!results.IsValid) 99 | { 100 | validationResponse.HasErrors = true; 101 | foreach (var error in results.Errors) 102 | { 103 | var ve = new ValidationError() 104 | { 105 | Message = error.ErrorMessage, 106 | MemberName = error.PropertyName 107 | }; 108 | validationResponse.Errors.Add(ve); 109 | } 110 | } 111 | else 112 | { 113 | validationResponse.HasErrors = false; 114 | } 115 | Validation = validationResponse; 116 | return validationResponse; 117 | } 118 | 119 | public ValidationResponse GetErrors() 120 | { 121 | return Validation; 122 | } 123 | 124 | public void AddError(string key, string message) 125 | { 126 | Validation.HasErrors = true; 127 | Validation.Errors.Add(new ValidationError() { MemberName = key, Message = message }); 128 | } 129 | 130 | public IResult Redirect(string url) 131 | { 132 | return Results.Redirect(url); 133 | } 134 | } 135 | 136 | -------------------------------------------------------------------------------- /BlazorMinimalApis/Lib/Session/SessionManager.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Components; 2 | using Microsoft.AspNetCore.Http; 3 | 4 | namespace BlazorMinimalApis.Lib.Session; 5 | 6 | public class SessionManager 7 | { 8 | private readonly IHttpContextAccessor _httpContextAccessor; 9 | 10 | public SessionManager(IHttpContextAccessor httpContextAccessor) 11 | { 12 | _httpContextAccessor = httpContextAccessor; 13 | } 14 | 15 | public void SetFlash(string key, string value) 16 | { 17 | if (_httpContextAccessor.HttpContext != null) 18 | { 19 | _httpContextAccessor.HttpContext.Session.SetString(key, value); 20 | } 21 | } 22 | 23 | public void SetString(string key, string value) 24 | { 25 | if (_httpContextAccessor.HttpContext != null) 26 | { 27 | _httpContextAccessor.HttpContext.Session.SetString(key, value); 28 | } 29 | } 30 | 31 | public string? GetString(string key) 32 | { 33 | if (_httpContextAccessor.HttpContext != null) 34 | { 35 | return _httpContextAccessor.HttpContext.Session.GetString(key); 36 | } 37 | return ""; 38 | } 39 | 40 | public string? GetFlash(string key) 41 | { 42 | if (_httpContextAccessor.HttpContext != null) 43 | { 44 | string? message = _httpContextAccessor.HttpContext.Session.GetString(key); 45 | _httpContextAccessor.HttpContext.Session.Remove(key); 46 | return message; 47 | } 48 | return ""; 49 | } 50 | 51 | public bool HasKey(string key) 52 | { 53 | if (_httpContextAccessor.HttpContext != null) 54 | { 55 | string? message = _httpContextAccessor.HttpContext.Session.GetString(key); 56 | return string.IsNullOrEmpty(message) ? false : true; 57 | } 58 | return false; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /BlazorMinimalApis/Lib/Validation/ValidationError.cs: -------------------------------------------------------------------------------- 1 | namespace BlazorMinimalApis.Lib.Validation; 2 | 3 | public class ValidationResponse 4 | { 5 | public bool HasErrors { get; set; } = true; 6 | public List Errors { get; set; } = new(); 7 | } 8 | 9 | public class ValidationError 10 | { 11 | public string Message { get; set; } 12 | public string MemberName { get; set; } 13 | } 14 | -------------------------------------------------------------------------------- /BlazorMinimalApis/Lib/Views/EmptyLayout.razor: -------------------------------------------------------------------------------- 1 | @inherits LayoutComponentBase 2 | 3 | @Body -------------------------------------------------------------------------------- /BlazorMinimalApis/Lib/Views/PageComponent.razor: -------------------------------------------------------------------------------- 1 | @using BlazorMinimalApis.Lib.Validation 2 | @using System.Collections.Concurrent 3 | @using System.Reflection 4 | 5 | 6 | @if (Layout != null) 7 | { 8 | 9 | 10 | 11 | } 12 | else 13 | { 14 | 15 | } 16 | 17 | 18 | @code { 19 | [Parameter, EditorRequired] 20 | public Type ComponentType { get; set; } 21 | 22 | [Parameter, EditorRequired] 23 | public Dictionary ComponentParameters { get; set; } 24 | 25 | [Parameter] 26 | public List Errors { get; set; } = new(); 27 | 28 | private PageState PageState { get; set; } = new(); 29 | 30 | private static readonly ConcurrentDictionary _layoutAttributeCache = new(); 31 | 32 | private Type? Layout = null; 33 | 34 | protected override async Task OnParametersSetAsync() 35 | { 36 | PageState.Errors = Errors; 37 | Layout = ComponentType.GetCustomAttribute()?.LayoutType; 38 | } 39 | } -------------------------------------------------------------------------------- /BlazorMinimalApis/Lib/Views/PageState.cs: -------------------------------------------------------------------------------- 1 | using BlazorMinimalApis.Lib.Validation; 2 | 3 | namespace BlazorMinimalApis.Lib.Views; 4 | 5 | public class PageState 6 | { 7 | public List Errors { get; set; } = new(); 8 | } 9 | -------------------------------------------------------------------------------- /BlazorMinimalApis/Lib/Views/XComponent.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Components.Rendering; 2 | using Microsoft.AspNetCore.Components; 3 | using System.Linq.Expressions; 4 | using Microsoft.AspNetCore.Components.Forms; 5 | using BlazorMinimalApis.Lib.Session; 6 | using BlazorMinimalApis.Lib.Validation; 7 | using Microsoft.AspNetCore.Http; 8 | using Microsoft.AspNetCore.Routing; 9 | 10 | namespace BlazorMinimalApis.Lib.Views; 11 | 12 | public class XComponent : IComponent 13 | { 14 | private readonly RenderFragment _renderFragment; 15 | private RenderHandle _renderHandle; 16 | private bool _initialized; 17 | private bool _hasNeverRendered = true; 18 | private bool _hasPendingQueuedRender; 19 | private bool _hasCalledOnAfterRender; 20 | [Inject] public LinkGenerator Link { get; set; } 21 | [Inject] public NavigationManager Navigation { get; set; } 22 | [Inject] IHttpContextAccessor HttpContextAccessor { get; set; } 23 | public List? Errors { get; set; } = new(); 24 | [CascadingParameter] PageState PageState { get; set; } 25 | SessionManager SessionManager; 26 | public bool HasErrors = false; 27 | protected string Message { get; set; } 28 | [Parameter] public TModel Model { get; set; } 29 | 30 | /// 31 | /// Constructs an instance of . 32 | /// 33 | public XComponent() 34 | { 35 | 36 | _renderFragment = builder => 37 | { 38 | _hasPendingQueuedRender = false; 39 | _hasNeverRendered = false; 40 | BuildRenderTree(builder); 41 | }; 42 | } 43 | 44 | public bool HasError(Expression>? For) 45 | { 46 | var _fieldIdentifier = FieldIdentifier.Create(For); 47 | 48 | if (!HasErrors) return false; 49 | 50 | var error = Errors.Where(x => x.MemberName == _fieldIdentifier.FieldName).FirstOrDefault(); 51 | 52 | if (error == null) return false; 53 | 54 | Message = error.Message; 55 | return true; 56 | } 57 | 58 | public string ValidationError(Expression>? For) 59 | { 60 | if (!HasErrors) return ""; 61 | 62 | var _fieldIdentifier = FieldIdentifier.Create(For); 63 | 64 | var error = Errors.Where(x => x.MemberName == _fieldIdentifier.FieldName).FirstOrDefault(); 65 | 66 | if (error == null) return ""; 67 | 68 | return error.Message; 69 | } 70 | 71 | public SessionManager Session() 72 | { 73 | return SessionManager; 74 | } 75 | 76 | /// 77 | /// Renders the component to the supplied . 78 | /// 79 | /// A that will receive the render output. 80 | protected virtual void BuildRenderTree(RenderTreeBuilder builder) 81 | { 82 | // Developers can either override this method in derived classes, or can use Razor 83 | // syntax to define a derived class and have the compiler generate the method. 84 | 85 | // Other code within this class should *not* invoke BuildRenderTree directly, 86 | // but instead should invoke the _renderFragment field. 87 | } 88 | 89 | void IComponent.Attach(RenderHandle renderHandle) 90 | { 91 | // This implicitly means a ComponentBase can only be associated with a single 92 | // renderer. That's the only use case we have right now. If there was ever a need, 93 | // a component could hold a collection of render handles. 94 | if (_renderHandle.IsInitialized) 95 | { 96 | throw new InvalidOperationException($"The render handle is already set. Cannot initialize a {nameof(ComponentBase)} more than once."); 97 | } 98 | 99 | _renderHandle = renderHandle; 100 | } 101 | 102 | /// 103 | /// Method invoked when the component is ready to start, having received its 104 | /// initial parameters from its parent in the render tree. 105 | /// 106 | protected virtual void OnInitialized() 107 | { 108 | } 109 | 110 | /// 111 | /// Method invoked when the component is ready to start, having received its 112 | /// initial parameters from its parent in the render tree. 113 | /// 114 | /// Override this method if you will perform an asynchronous operation and 115 | /// want the component to refresh when that operation is completed. 116 | /// 117 | /// A representing any asynchronous operation. 118 | protected virtual Task OnInitializedAsync() 119 | => Task.CompletedTask; 120 | 121 | /// 122 | /// Method invoked when the component has received parameters from its parent in 123 | /// the render tree, and the incoming values have been assigned to properties. 124 | /// 125 | protected virtual void OnParametersSet() 126 | { 127 | } 128 | 129 | /// 130 | /// Method invoked when the component has received parameters from its parent in 131 | /// the render tree, and the incoming values have been assigned to properties. 132 | /// 133 | /// A representing any asynchronous operation. 134 | protected virtual Task OnParametersSetAsync() 135 | => Task.CompletedTask; 136 | 137 | /// 138 | /// Notifies the component that its state has changed. When applicable, this will 139 | /// cause the component to be re-rendered. 140 | /// 141 | protected void StateHasChanged() 142 | { 143 | if (_hasPendingQueuedRender) 144 | { 145 | return; 146 | } 147 | 148 | if (_hasNeverRendered || ShouldRender() || _renderHandle.IsRenderingOnMetadataUpdate) 149 | { 150 | _hasPendingQueuedRender = true; 151 | 152 | try 153 | { 154 | _renderHandle.Render(_renderFragment); 155 | } 156 | catch 157 | { 158 | _hasPendingQueuedRender = false; 159 | throw; 160 | } 161 | } 162 | } 163 | 164 | /// 165 | /// Returns a flag to indicate whether the component should render. 166 | /// 167 | /// 168 | protected virtual bool ShouldRender() 169 | => true; 170 | 171 | /// 172 | /// Executes the supplied work item on the associated renderer's 173 | /// synchronization context. 174 | /// 175 | /// The work item to execute. 176 | protected Task InvokeAsync(Action workItem) 177 | => _renderHandle.Dispatcher.InvokeAsync(workItem); 178 | 179 | /// 180 | /// Executes the supplied work item on the associated renderer's 181 | /// synchronization context. 182 | /// 183 | /// The work item to execute. 184 | protected Task InvokeAsync(Func workItem) 185 | => _renderHandle.Dispatcher.InvokeAsync(workItem); 186 | 187 | /// 188 | /// Treats the supplied as being thrown by this component. This will cause the 189 | /// enclosing ErrorBoundary to transition into a failed state. If there is no enclosing ErrorBoundary, 190 | /// it will be regarded as an exception from the enclosing renderer. 191 | /// 192 | /// This is useful if an exception occurs outside the component lifecycle methods, but you wish to treat it 193 | /// the same as an exception from a component lifecycle method. 194 | /// 195 | /// The that will be dispatched to the renderer. 196 | /// A that will be completed when the exception has finished dispatching. 197 | protected Task DispatchExceptionAsync(Exception exception) 198 | => _renderHandle.DispatchExceptionAsync(exception); 199 | 200 | /// 201 | /// Sets parameters supplied by the component's parent in the render tree. 202 | /// 203 | /// The parameters. 204 | /// A that completes when the component has finished updating and rendering itself. 205 | /// 206 | /// 207 | /// Parameters are passed when is called. It is not required that 208 | /// the caller supply a parameter value for all of the parameters that are logically understood by the component. 209 | /// 210 | /// 211 | /// The default implementation of will set the value of each property 212 | /// decorated with or that has 213 | /// a corresponding value in the . Parameters that do not have a corresponding value 214 | /// will be unchanged. 215 | /// 216 | /// 217 | public virtual Task SetParametersAsync(ParameterView parameters) 218 | { 219 | parameters.SetParameterProperties(this); 220 | if (!_initialized) 221 | { 222 | _initialized = true; 223 | 224 | return RunInitAndSetParametersAsync(); 225 | } 226 | else 227 | { 228 | return CallOnParametersSetAsync(); 229 | } 230 | } 231 | 232 | private async Task RunInitAndSetParametersAsync() 233 | { 234 | OnInitialized(); 235 | var task = OnInitializedAsync(); 236 | 237 | if (task.Status != TaskStatus.RanToCompletion && task.Status != TaskStatus.Canceled) 238 | { 239 | // Call state has changed here so that we render after the sync part of OnInitAsync has run 240 | // and wait for it to finish before we continue. If no async work has been done yet, we want 241 | // to defer calling StateHasChanged up until the first bit of async code happens or until 242 | // the end. Additionally, we want to avoid calling StateHasChanged if no 243 | // async work is to be performed. 244 | StateHasChanged(); 245 | 246 | try 247 | { 248 | await task; 249 | } 250 | catch // avoiding exception filters for AOT runtime support 251 | { 252 | // Ignore exceptions from task cancellations. 253 | // Awaiting a canceled task may produce either an OperationCanceledException (if produced as a consequence of 254 | // CancellationToken.ThrowIfCancellationRequested()) or a TaskCanceledException (produced as a consequence of awaiting Task.FromCanceled). 255 | // It's much easier to check the state of the Task (i.e. Task.IsCanceled) rather than catch two distinct exceptions. 256 | if (!task.IsCanceled) 257 | { 258 | throw; 259 | } 260 | } 261 | 262 | // Don't call StateHasChanged here. CallOnParametersSetAsync should handle that for us. 263 | } 264 | 265 | await CallOnParametersSetAsync(); 266 | } 267 | 268 | private Task CallOnParametersSetAsync() 269 | { 270 | Errors = PageState.Errors; 271 | if (Errors != null && Errors.Count > 0) 272 | { 273 | HasErrors = true; 274 | } 275 | SessionManager = new SessionManager(HttpContextAccessor); 276 | 277 | OnParametersSet(); 278 | var task = OnParametersSetAsync(); 279 | 280 | // If no async work is to be performed, i.e. the task has already ran to completion 281 | // or was canceled by the time we got to inspect it, avoid going async and re-invoking 282 | // StateHasChanged at the culmination of the async work. 283 | var shouldAwaitTask = task.Status != TaskStatus.RanToCompletion && 284 | task.Status != TaskStatus.Canceled; 285 | 286 | // We always call StateHasChanged here as we want to trigger a rerender after OnParametersSet and 287 | // the synchronous part of OnParametersSetAsync has run. 288 | StateHasChanged(); 289 | 290 | return shouldAwaitTask ? 291 | CallStateHasChangedOnAsyncCompletion(task) : 292 | Task.CompletedTask; 293 | } 294 | 295 | private async Task CallStateHasChangedOnAsyncCompletion(Task task) 296 | { 297 | try 298 | { 299 | await task; 300 | } 301 | catch // avoiding exception filters for AOT runtime support 302 | { 303 | // Ignore exceptions from task cancellations, but don't bother issuing a state change. 304 | if (task.IsCanceled) 305 | { 306 | return; 307 | } 308 | 309 | throw; 310 | } 311 | 312 | StateHasChanged(); 313 | } 314 | } 315 | 316 | 317 | public class XComponent : IComponent 318 | { 319 | private readonly RenderFragment _renderFragment; 320 | private RenderHandle _renderHandle; 321 | private bool _initialized; 322 | private bool _hasNeverRendered = true; 323 | private bool _hasPendingQueuedRender; 324 | private bool _hasCalledOnAfterRender; 325 | [Inject] public LinkGenerator Link { get; set; } 326 | [Inject] public NavigationManager Navigation { get; set; } 327 | [Inject] IHttpContextAccessor HttpContextAccessor { get; set; } 328 | public List? Errors { get; set; } = new(); 329 | [CascadingParameter] PageState PageState { get; set; } 330 | SessionManager SessionManager; 331 | public bool HasErrors = false; 332 | protected string Message { get; set; } 333 | 334 | /// 335 | /// Constructs an instance of . 336 | /// 337 | public XComponent() 338 | { 339 | 340 | _renderFragment = builder => 341 | { 342 | _hasPendingQueuedRender = false; 343 | _hasNeverRendered = false; 344 | BuildRenderTree(builder); 345 | }; 346 | } 347 | 348 | public bool HasError(Expression>? For) 349 | { 350 | var _fieldIdentifier = FieldIdentifier.Create(For); 351 | 352 | if (!HasErrors) return false; 353 | 354 | var error = Errors.Where(x => x.MemberName == _fieldIdentifier.FieldName).FirstOrDefault(); 355 | 356 | if (error == null) return false; 357 | 358 | Message = error.Message; 359 | return true; 360 | } 361 | 362 | public string ValidationError(Expression>? For) 363 | { 364 | if (!HasErrors) return ""; 365 | 366 | var _fieldIdentifier = FieldIdentifier.Create(For); 367 | 368 | var error = Errors.Where(x => x.MemberName == _fieldIdentifier.FieldName).FirstOrDefault(); 369 | 370 | if (error == null) return ""; 371 | 372 | return error.Message; 373 | } 374 | 375 | public SessionManager Session() 376 | { 377 | return SessionManager; 378 | } 379 | 380 | /// 381 | /// Renders the component to the supplied . 382 | /// 383 | /// A that will receive the render output. 384 | protected virtual void BuildRenderTree(RenderTreeBuilder builder) 385 | { 386 | // Developers can either override this method in derived classes, or can use Razor 387 | // syntax to define a derived class and have the compiler generate the method. 388 | 389 | // Other code within this class should *not* invoke BuildRenderTree directly, 390 | // but instead should invoke the _renderFragment field. 391 | } 392 | 393 | void IComponent.Attach(RenderHandle renderHandle) 394 | { 395 | // This implicitly means a ComponentBase can only be associated with a single 396 | // renderer. That's the only use case we have right now. If there was ever a need, 397 | // a component could hold a collection of render handles. 398 | if (_renderHandle.IsInitialized) 399 | { 400 | throw new InvalidOperationException($"The render handle is already set. Cannot initialize a {nameof(ComponentBase)} more than once."); 401 | } 402 | 403 | _renderHandle = renderHandle; 404 | } 405 | 406 | /// 407 | /// Method invoked when the component is ready to start, having received its 408 | /// initial parameters from its parent in the render tree. 409 | /// 410 | protected virtual void OnInitialized() 411 | { 412 | } 413 | 414 | /// 415 | /// Method invoked when the component is ready to start, having received its 416 | /// initial parameters from its parent in the render tree. 417 | /// 418 | /// Override this method if you will perform an asynchronous operation and 419 | /// want the component to refresh when that operation is completed. 420 | /// 421 | /// A representing any asynchronous operation. 422 | protected virtual Task OnInitializedAsync() 423 | => Task.CompletedTask; 424 | 425 | /// 426 | /// Method invoked when the component has received parameters from its parent in 427 | /// the render tree, and the incoming values have been assigned to properties. 428 | /// 429 | protected virtual void OnParametersSet() 430 | { 431 | } 432 | 433 | /// 434 | /// Method invoked when the component has received parameters from its parent in 435 | /// the render tree, and the incoming values have been assigned to properties. 436 | /// 437 | /// A representing any asynchronous operation. 438 | protected virtual Task OnParametersSetAsync() 439 | => Task.CompletedTask; 440 | 441 | /// 442 | /// Notifies the component that its state has changed. When applicable, this will 443 | /// cause the component to be re-rendered. 444 | /// 445 | protected void StateHasChanged() 446 | { 447 | if (_hasPendingQueuedRender) 448 | { 449 | return; 450 | } 451 | 452 | if (_hasNeverRendered || ShouldRender() || _renderHandle.IsRenderingOnMetadataUpdate) 453 | { 454 | _hasPendingQueuedRender = true; 455 | 456 | try 457 | { 458 | _renderHandle.Render(_renderFragment); 459 | } 460 | catch 461 | { 462 | _hasPendingQueuedRender = false; 463 | throw; 464 | } 465 | } 466 | } 467 | 468 | /// 469 | /// Returns a flag to indicate whether the component should render. 470 | /// 471 | /// 472 | protected virtual bool ShouldRender() 473 | => true; 474 | 475 | /// 476 | /// Executes the supplied work item on the associated renderer's 477 | /// synchronization context. 478 | /// 479 | /// The work item to execute. 480 | protected Task InvokeAsync(Action workItem) 481 | => _renderHandle.Dispatcher.InvokeAsync(workItem); 482 | 483 | /// 484 | /// Executes the supplied work item on the associated renderer's 485 | /// synchronization context. 486 | /// 487 | /// The work item to execute. 488 | protected Task InvokeAsync(Func workItem) 489 | => _renderHandle.Dispatcher.InvokeAsync(workItem); 490 | 491 | /// 492 | /// Treats the supplied as being thrown by this component. This will cause the 493 | /// enclosing ErrorBoundary to transition into a failed state. If there is no enclosing ErrorBoundary, 494 | /// it will be regarded as an exception from the enclosing renderer. 495 | /// 496 | /// This is useful if an exception occurs outside the component lifecycle methods, but you wish to treat it 497 | /// the same as an exception from a component lifecycle method. 498 | /// 499 | /// The that will be dispatched to the renderer. 500 | /// A that will be completed when the exception has finished dispatching. 501 | protected Task DispatchExceptionAsync(Exception exception) 502 | => _renderHandle.DispatchExceptionAsync(exception); 503 | 504 | /// 505 | /// Sets parameters supplied by the component's parent in the render tree. 506 | /// 507 | /// The parameters. 508 | /// A that completes when the component has finished updating and rendering itself. 509 | /// 510 | /// 511 | /// Parameters are passed when is called. It is not required that 512 | /// the caller supply a parameter value for all of the parameters that are logically understood by the component. 513 | /// 514 | /// 515 | /// The default implementation of will set the value of each property 516 | /// decorated with or that has 517 | /// a corresponding value in the . Parameters that do not have a corresponding value 518 | /// will be unchanged. 519 | /// 520 | /// 521 | public virtual Task SetParametersAsync(ParameterView parameters) 522 | { 523 | parameters.SetParameterProperties(this); 524 | if (!_initialized) 525 | { 526 | _initialized = true; 527 | 528 | return RunInitAndSetParametersAsync(); 529 | } 530 | else 531 | { 532 | return CallOnParametersSetAsync(); 533 | } 534 | } 535 | 536 | private async Task RunInitAndSetParametersAsync() 537 | { 538 | OnInitialized(); 539 | var task = OnInitializedAsync(); 540 | 541 | if (task.Status != TaskStatus.RanToCompletion && task.Status != TaskStatus.Canceled) 542 | { 543 | // Call state has changed here so that we render after the sync part of OnInitAsync has run 544 | // and wait for it to finish before we continue. If no async work has been done yet, we want 545 | // to defer calling StateHasChanged up until the first bit of async code happens or until 546 | // the end. Additionally, we want to avoid calling StateHasChanged if no 547 | // async work is to be performed. 548 | StateHasChanged(); 549 | 550 | try 551 | { 552 | await task; 553 | } 554 | catch // avoiding exception filters for AOT runtime support 555 | { 556 | // Ignore exceptions from task cancellations. 557 | // Awaiting a canceled task may produce either an OperationCanceledException (if produced as a consequence of 558 | // CancellationToken.ThrowIfCancellationRequested()) or a TaskCanceledException (produced as a consequence of awaiting Task.FromCanceled). 559 | // It's much easier to check the state of the Task (i.e. Task.IsCanceled) rather than catch two distinct exceptions. 560 | if (!task.IsCanceled) 561 | { 562 | throw; 563 | } 564 | } 565 | 566 | // Don't call StateHasChanged here. CallOnParametersSetAsync should handle that for us. 567 | } 568 | 569 | await CallOnParametersSetAsync(); 570 | } 571 | 572 | private Task CallOnParametersSetAsync() 573 | { 574 | Errors = PageState.Errors; 575 | if (Errors != null && Errors.Count > 0) 576 | { 577 | HasErrors = true; 578 | } 579 | SessionManager = new SessionManager(HttpContextAccessor); 580 | 581 | OnParametersSet(); 582 | var task = OnParametersSetAsync(); 583 | 584 | // If no async work is to be performed, i.e. the task has already ran to completion 585 | // or was canceled by the time we got to inspect it, avoid going async and re-invoking 586 | // StateHasChanged at the culmination of the async work. 587 | var shouldAwaitTask = task.Status != TaskStatus.RanToCompletion && 588 | task.Status != TaskStatus.Canceled; 589 | 590 | // We always call StateHasChanged here as we want to trigger a rerender after OnParametersSet and 591 | // the synchronous part of OnParametersSetAsync has run. 592 | StateHasChanged(); 593 | 594 | return shouldAwaitTask ? 595 | CallStateHasChangedOnAsyncCompletion(task) : 596 | Task.CompletedTask; 597 | } 598 | 599 | private async Task CallStateHasChangedOnAsyncCompletion(Task task) 600 | { 601 | try 602 | { 603 | await task; 604 | } 605 | catch // avoiding exception filters for AOT runtime support 606 | { 607 | // Ignore exceptions from task cancellations, but don't bother issuing a state change. 608 | if (task.IsCanceled) 609 | { 610 | return; 611 | } 612 | 613 | throw; 614 | } 615 | 616 | StateHasChanged(); 617 | } 618 | } 619 | -------------------------------------------------------------------------------- /BlazorMinimalApis/Lib/Views/XLayout.razor: -------------------------------------------------------------------------------- 1 | @using Htmx; 2 | @using Microsoft.AspNetCore.Http 3 | @inject IServiceProvider ServiceProvider 4 | 5 | 6 | @ChildContent 7 | 8 | 9 | @code { 10 | [Parameter, EditorRequired] 11 | public Type Layout { get; set; } 12 | 13 | [Parameter] public required RenderFragment ChildContent { get; set; } 14 | 15 | private IHttpContextAccessor accessor; 16 | 17 | protected override void OnParametersSet() 18 | { 19 | // determine layout 20 | accessor = (IHttpContextAccessor)ServiceProvider.GetService(typeof(IHttpContextAccessor)); 21 | if (accessor != null) 22 | { 23 | var context = accessor.HttpContext; 24 | 25 | // override layout if it's a htmx request that isn't a boosted navigation 26 | if (context != null && context.Request.IsHtmx() && !context.Request.IsHtmxBoosted()) 27 | { 28 | Layout = typeof(EmptyLayout); 29 | } 30 | } 31 | } 32 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # .NET Minimal APIS, Razor Components, and HTMX 2 | This is a demo on how to use Minimal APIs + Razor Components + HTMX to create dynamic server side rendered apps. 3 | 4 | Using Minimal APIs and Razor components is possible because of a new class in .NET 8: **RazorComponentResult** 5 | 6 | This returns an IResult after initializing a Razor component, making it possible to use Razor components in Minimal APIs. 7 | 8 | ## Requirements 9 | 10 | Requires .NET 8 RC1 installed. 11 | 12 | ## Why do this? 13 | 14 | Minimal APIs are a great way to organize your app. 1 endpoint corresponds to 1 method in a handler class. Simple and effective. 15 | 16 | Razor components are great because you can re-use markup. But with Blazor WASM and Server, you are relying on a lot of magic and niche web technologies (web assembly and web sockets). With this setup, you are simply making normal HTTP requests and returning markup. 17 | 18 | Pairing these 2 things together is an easy way to create maintainable, straightforward server side web apps. Add HTMX to this combination and you can build very powerful interfaces. 19 | 20 | ## HTMX Usage 21 | 22 | ### Partial page reload on navigation with hx-boost 23 | 24 | The HTMX attribute hx-boost turns internal links into ajax calls. This speeds up site speed since there are no full page reloads. You can opt in and out of this behavior on a link by link basis. 25 | 26 | This app uses hx-boost on the body tag, turning on this functionality for all links. 27 | 28 | ### Get and Post requests with hx-get and hx-post 29 | 30 | The HTMX attributes hx-get and hx-post sets up ajax calls to endpoints and swaps html on the page with what was returned. 31 | 32 | This is useful for submitting forms, searching tables, and modifying the dom from a user interaction on the page. 33 | 34 | ### Polling 35 | 36 | The HTMX attribute hx-trigger can be used to poll the server. This can setup ajax calls to endpoints at an interval and swap html on the page with what was returned. 37 | 38 | This is demonstrated on the /Components/Pages/Home.razor page in combination with the /Components/Pages/RandomNumber.razor component. -------------------------------------------------------------------------------- /Samples/BlazorMinimalApi.Pages/BlazorMinimalApis.Pages.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net8.0 5 | enable 6 | enable 7 | BlazorMinimalApis.Pages 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | <_ContentIncludedByDefault Remove="Lib\Views\EmptyLayout.razor" /> 16 | <_ContentIncludedByDefault Remove="Lib\Views\PageComponent.razor" /> 17 | <_ContentIncludedByDefault Remove="Lib\Views\XLayout.razor" /> 18 | <_ContentIncludedByDefault Remove="Endpoints\Pages\Contacts\ContactsSearchTable.razor" /> 19 | <_ContentIncludedByDefault Remove="Endpoints\Pages\Contacts\Create.razor" /> 20 | <_ContentIncludedByDefault Remove="Endpoints\Pages\Contacts\Edit.razor" /> 21 | <_ContentIncludedByDefault Remove="Endpoints\Pages\Contacts\List.razor" /> 22 | <_ContentIncludedByDefault Remove="Endpoints\Pages\Home\Home.razor" /> 23 | <_ContentIncludedByDefault Remove="Endpoints\Pages\Home\RandomNumber.razor" /> 24 | <_ContentIncludedByDefault Remove="Endpoints\Pages\Shared\FlashMessages.razor" /> 25 | <_ContentIncludedByDefault Remove="Endpoints\Pages\Shared\Layout\MainLayout.razor" /> 26 | <_ContentIncludedByDefault Remove="Endpoints\Pages\_Imports.razor" /> 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /Samples/BlazorMinimalApi.Pages/Data/Database.cs: -------------------------------------------------------------------------------- 1 | namespace BlazorMinimalApis.Pages.Data; 2 | 3 | public static class Database 4 | { 5 | public static List Contacts = new() 6 | { 7 | new Contact { Id = 1, Name = "Kramer", Email = "kramer@gmail.com", City = "New York", Phone = "3927374545" }, 8 | new Contact { Id = 2, Name = "Jerry", Email = "Jerry@gmail.com", City = "Queens", Phone = "3954563237" } 9 | }; 10 | 11 | } 12 | 13 | public class Contact 14 | { 15 | public int Id { get; set; } 16 | public string Name { get; set; } 17 | public string Email { get; set; } 18 | public string City { get; set; } 19 | public string Phone { get; set; } 20 | } 21 | -------------------------------------------------------------------------------- /Samples/BlazorMinimalApi.Pages/Lib/IRouteDefinition.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Builder; 2 | 3 | namespace BlazorMinimalApis.Pages.Lib; 4 | 5 | public interface IRouteDefinition 6 | { 7 | void Map(WebApplication app); 8 | } -------------------------------------------------------------------------------- /Samples/BlazorMinimalApi.Pages/Lib/RegisterRoutesExtension.cs: -------------------------------------------------------------------------------- 1 | using BlazorMinimalApis.Lib.Routing; 2 | using Microsoft.AspNetCore.Builder; 3 | 4 | namespace BlazorMinimalApis.Pages.Lib; 5 | 6 | public static class RegisterRoutesExtension 7 | { 8 | public static void RegisterRoutes(this WebApplication app) 9 | { 10 | var endpointDefinitions = typeof(Program).Assembly 11 | .GetTypes() 12 | .Where(t => t.IsAssignableTo(typeof(IRouteDefinition)) 13 | && !t.IsAbstract && !t.IsInterface) 14 | .Select(Activator.CreateInstance) 15 | .Cast(); 16 | 17 | foreach (var endpointDef in endpointDefinitions) 18 | { 19 | endpointDef.Map(app); 20 | } 21 | } 22 | } -------------------------------------------------------------------------------- /Samples/BlazorMinimalApi.Pages/Pages/Api/Contacts/ListContacts.cs: -------------------------------------------------------------------------------- 1 | using BlazorMinimalApis.Pages.Data; 2 | using BlazorMinimalApis.Lib.Routing; 3 | using BlazorMinimalApis.Pages.Lib; 4 | 5 | namespace BlazorMinimalApis.Pages.Pages.Api.Contacts; 6 | 7 | public class ListContacts : XPage 8 | { 9 | public IResult Get() 10 | { 11 | var data = new { Contacts = Database.Contacts }; 12 | return Results.Ok(data); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Samples/BlazorMinimalApi.Pages/Pages/Contacts/CreateContact.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | using BlazorMinimalApis.Pages.Data; 3 | using BlazorMinimalApis.Lib.Routing; 4 | using BlazorMinimalApis.Lib.Session; 5 | using BlazorMinimalApis.Pages.Lib; 6 | using Microsoft.AspNetCore.Mvc; 7 | using Riok.Mapperly.Abstractions; 8 | 9 | namespace BlazorMinimalApis.Pages.Pages.Contacts; 10 | 11 | public class CreateContact : XPage 12 | { 13 | public CreateContactForm Form = new(); 14 | 15 | public IResult Get() 16 | { 17 | Form = new CreateContactForm(); 18 | return Page<_CreateContact>(); 19 | } 20 | 21 | public IResult Post([FromForm] CreateContactForm form, SessionManager Session) 22 | { 23 | if (Validate(form).HasErrors) 24 | { 25 | Form = form; 26 | return Page<_CreateContact>(); 27 | } 28 | var newContact = new CreateContactMapper().FormToContact(form); 29 | newContact.Id = Database.Contacts.Count() + 1; 30 | Database.Contacts.Add(newContact); 31 | 32 | Session.SetFlash("success", "Contact successfully added."); 33 | return Redirect("/contacts/create"); 34 | } 35 | } 36 | 37 | public class CreateContactForm 38 | { 39 | [Required] public string Name { get; set; } 40 | [Required, EmailAddress] public string Email { get; set; } 41 | [Required] public string City { get; set; } 42 | [Required, Phone] public string Phone { get; set; } 43 | } 44 | 45 | 46 | [Mapper] 47 | public partial class CreateContactMapper 48 | { 49 | public partial CreateContactForm ContactToForm(Contact contact); 50 | public partial Contact FormToContact(CreateContactForm contact); 51 | } -------------------------------------------------------------------------------- /Samples/BlazorMinimalApi.Pages/Pages/Contacts/DeleteContact.cs: -------------------------------------------------------------------------------- 1 | using BlazorMinimalApis.Pages.Data; 2 | using BlazorMinimalApis.Lib.Routing; 3 | using BlazorMinimalApis.Pages.Lib; 4 | 5 | namespace BlazorMinimalApis.Pages.Pages.Contacts; 6 | 7 | public class DeleteContact : XPage 8 | { 9 | public IResult Get(int id) 10 | { 11 | var contact = Database.Contacts.First(x => x.Id == id); 12 | Database.Contacts.Remove(contact); 13 | return Redirect($"/contacts"); 14 | } 15 | } -------------------------------------------------------------------------------- /Samples/BlazorMinimalApi.Pages/Pages/Contacts/EditContact.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | using BlazorMinimalApis.Pages.Data; 3 | using BlazorMinimalApis.Lib.Routing; 4 | using BlazorMinimalApis.Pages.Lib; 5 | using Microsoft.AspNetCore.Mvc; 6 | using Riok.Mapperly.Abstractions; 7 | 8 | namespace BlazorMinimalApis.Pages.Pages.Contacts; 9 | 10 | public class EditContact : XPage 11 | { 12 | public EditContactForm Form = new(); 13 | public int Id; 14 | 15 | public IResult Get(int id) 16 | { 17 | var record = Database.Contacts.Where(x => x.Id == id).First(); 18 | Form = new EditContactMapper().ContactToForm(record); 19 | Id = id; 20 | return Page<_EditContact>(); 21 | } 22 | 23 | public IResult Post(int id, [FromForm] EditContactForm form) 24 | { 25 | var validation = Validate(form); 26 | if (validation.HasErrors) 27 | { 28 | Id = id; 29 | Form = form; 30 | return Page<_EditContact>(); 31 | } 32 | var oldContact = Database.Contacts.First(x => x.Id == id); 33 | var newContact = new EditContactMapper().FormToContact(form); 34 | newContact.Id = oldContact.Id; 35 | Database.Contacts.Add(newContact); 36 | Database.Contacts.Remove(oldContact); 37 | 38 | return Redirect($"/contacts/{newContact.Id}/edit"); 39 | } 40 | } 41 | 42 | public class EditContactForm 43 | { 44 | [Required] public string Name { get; set; } 45 | [Required, EmailAddress] public string Email { get; set; } 46 | [Required] public string City { get; set; } 47 | [Required, Phone] public string Phone { get; set; } 48 | } 49 | 50 | [Mapper] 51 | public partial class EditContactMapper 52 | { 53 | public partial EditContactForm ContactToForm(Contact contact); 54 | public partial Contact FormToContact(EditContactForm contact); 55 | } -------------------------------------------------------------------------------- /Samples/BlazorMinimalApi.Pages/Pages/Contacts/ListContacts.cs: -------------------------------------------------------------------------------- 1 | using BlazorMinimalApis.Pages.Data; 2 | using BlazorMinimalApis.Lib.Routing; 3 | using BlazorMinimalApis.Pages.Lib; 4 | using Microsoft.AspNetCore.Mvc; 5 | 6 | namespace BlazorMinimalApis.Pages.Pages.Contacts; 7 | 8 | public class ListContacts : XPage 9 | { 10 | public List Contacts = new(); 11 | 12 | public IResult Get(HttpContext context) 13 | { 14 | Contacts = Database.Contacts; 15 | return Page<_ListContacts>(); 16 | } 17 | 18 | public IResult GetSearch([FromQuery] string ContactSearch) 19 | { 20 | Contacts = Database.Contacts 21 | .Where(x => x.Name.Contains(ContactSearch, StringComparison.OrdinalIgnoreCase)) 22 | .ToList(); 23 | 24 | return Page<_SearchContacts>(); 25 | } 26 | } -------------------------------------------------------------------------------- /Samples/BlazorMinimalApi.Pages/Pages/Contacts/_CreateContact.razor: -------------------------------------------------------------------------------- 1 | @inherits XComponent 2 | @layout MainLayout 3 | 4 | Add contacts 5 | 6 |

7 | 8 | Contacts 9 | 10 | / 11 | Create 12 |

13 | 14 | 15 | 16 |
17 |
18 |
19 |
20 | 21 | 22 | @if (HasError(() => Model.Form.Name)) 23 | { 24 |
@Message
25 | } 26 |
27 |
28 | 29 | 30 | @if (HasError(() => Model.Form.Email)) 31 | { 32 |
@Message
33 | } 34 |
35 |
36 | 37 | 38 | @if (HasError(() => Model.Form.City)) 39 | { 40 |
@Message
41 | } 42 |
43 |
44 | 45 | 46 | @if (HasError(() => Model.Form.Phone)) 47 | { 48 |
@Message
49 | } 50 |
51 |
52 |
53 | 56 |
57 | 58 | 59 |
-------------------------------------------------------------------------------- /Samples/BlazorMinimalApi.Pages/Pages/Contacts/_EditContact.razor: -------------------------------------------------------------------------------- 1 | @inherits XComponent 2 | @layout MainLayout 3 | 4 | Edit contacts 5 | 6 |

7 | Contacts 8 | / 9 | @Model.Form.Name 10 |

11 |
12 |
13 |
14 |
15 | 16 | 17 | @if (HasError(() => Model.Form.Name)) 18 | { 19 |
@Message
20 | } 21 |
22 |
23 | 24 | 25 | @if (HasError(() => Model.Form.Email)) 26 | { 27 |
@Message
28 | } 29 |
30 |
31 | 32 | 33 | @if (HasError(() => Model.Form.City)) 34 | { 35 |
@Message
36 | } 37 |
38 |
39 | 40 | 41 | @if (HasError(() => Model.Form.Phone)) 42 | { 43 |
@Message
44 | } 45 |
46 |
47 |
48 | Delete Contact 49 | 52 |
53 | 54 | 55 |
-------------------------------------------------------------------------------- /Samples/BlazorMinimalApi.Pages/Pages/Contacts/_ListContacts.razor: -------------------------------------------------------------------------------- 1 | @inherits XComponent 2 | @layout MainLayout 3 | 4 | Contacts 5 | 6 |

7 | Contacts 8 |

9 |
10 |
11 | 12 |
13 | Add contact 14 |
15 | 16 |
17 |
18 | <_SearchContacts Model="Model" /> 19 |
20 |
21 | -------------------------------------------------------------------------------- /Samples/BlazorMinimalApi.Pages/Pages/Contacts/_SearchContacts.razor: -------------------------------------------------------------------------------- 1 | @inherits XComponent 2 | 3 |
4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | @if (Model.Contacts.Count <= 0) 12 | { 13 | 14 | 15 | 16 | } 17 | @foreach (var contact in Model.Contacts) 18 | { 19 | 20 | 25 | 30 | 35 | 40 | 41 | } 42 |
NameEmailCityPhone
No contacts with that name found.
21 | 22 | @contact.Name 23 | 24 | 26 | 27 | @contact.Email 28 | 29 | 31 | 32 | @contact.City 33 | 34 | 36 | 37 | @contact.Phone 38 | 39 |
43 |
44 | -------------------------------------------------------------------------------- /Samples/BlazorMinimalApi.Pages/Pages/Home/Home.cs: -------------------------------------------------------------------------------- 1 | using BlazorMinimalApis.Lib.Routing; 2 | using BlazorMinimalApis.Pages.Lib; 3 | using System; 4 | 5 | namespace BlazorMinimalApis.Pages.Pages.Home; 6 | 7 | public class Home : XPage 8 | { 9 | public int Num; 10 | 11 | public IResult Get() 12 | { 13 | return Page<_Home>(); 14 | } 15 | 16 | public IResult RandomNumber() 17 | { 18 | Random rnd = new Random(); 19 | Num = rnd.Next(); 20 | return Page<_RandomNumber>(); 21 | } 22 | } -------------------------------------------------------------------------------- /Samples/BlazorMinimalApi.Pages/Pages/Home/_Home.razor: -------------------------------------------------------------------------------- 1 | @inherits XComponent 2 | @layout MainLayout 3 | 4 | Home 5 | 6 |
7 |

8 | Welcome to the contact manager 9 |

10 |

This is a demo on how to use Minimal APIs + Razor Components + HTMX to create dynamic server side rendered apps.

11 | Explore the crud example 12 |

13 | You can check out the repo here 14 |

15 |

16 | Using Minimal APIs and Razor components is possible because of a new class in .NET 8: RazorComponentResult 17 |

18 |

This returns an IResult after initializing a Razor component, making it possible to use Razor components in Minimal APIs.

19 |

20 | Requirements 21 |

22 |

23 | Requires .NET 8 RC1 installed. 24 |

25 |

26 | Partial page reload on navigation with hx-boost 27 |

28 |

29 | The HTMX attribute hx-boost turns internal links into ajax calls. This speeds up site speed since there are no full page reloads. You can opt in and out of this behavior on a link by link basis. 30 |

31 |

32 | This app uses hx-boost on the body tag, turning on this functionality for all links. 33 |

34 |

35 | Get and Post requests with hx-get and hx-post 36 |

37 |

38 | The HTMX attributes hx-get and hx-post sets up ajax calls to endpoints and swaps html on the page with what was returned. 39 |

40 |

41 | This is useful for submitting forms, searching tables, and modifying the dom from a user interaction on the page. 42 |

43 |

44 | Polling 45 |

46 |

47 | The HTMX attribute hx-trigger can be used to poll the server. This can setup ajax calls to endpoints at an interval and swap html on the page with what was returned. 48 |

49 |

50 | Below is random number generator. 51 |

52 |
53 |
54 | <_RandomNumber Model="Model" /> 55 |
56 |
57 |

58 | HTMX calls /random-number every 2s and replaces the html with the html returned by the endpoint. 59 |

60 |
-------------------------------------------------------------------------------- /Samples/BlazorMinimalApi.Pages/Pages/Home/_RandomNumber.razor: -------------------------------------------------------------------------------- 1 | @inherits XComponent 2 | 3 |

Random Number is @Model.Num

4 | -------------------------------------------------------------------------------- /Samples/BlazorMinimalApi.Pages/Pages/Shared/FlashMessages.razor: -------------------------------------------------------------------------------- 1 | @inherits XComponent 2 | 3 | @if (Session().HasKey("success")) 4 | { 5 |
6 | @Session().GetFlash("success") 7 |
8 | } -------------------------------------------------------------------------------- /Samples/BlazorMinimalApi.Pages/Pages/Shared/Layout/MainLayout.razor: -------------------------------------------------------------------------------- 1 | @inherits LayoutComponentBase 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 |
21 |
22 |

Contact Manager

23 |

John Doe

24 |
25 |
26 |
27 |
28 | @Body 29 |
30 |
31 |
32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /Samples/BlazorMinimalApi.Pages/Pages/_Imports.razor: -------------------------------------------------------------------------------- 1 | @using System.Net.Http 2 | @using System.Net.Http.Json 3 | @using Microsoft.AspNetCore.Components.Forms 4 | @using Microsoft.AspNetCore.Components.Routing 5 | @using Microsoft.AspNetCore.Components.Web 6 | @using Microsoft.AspNetCore.Components.Web.Virtualization 7 | @using Microsoft.JSInterop 8 | @using Microsoft.AspNetCore.Authorization 9 | @using BlazorMinimalApis 10 | @using BlazorMinimalApis.Pages.Pages 11 | @using BlazorMinimalApis.Pages.Pages.Shared 12 | @using BlazorMinimalApis.Pages.Pages.Shared.Layout 13 | @using BlazorMinimalApis.Pages.Data 14 | @using BlazorMinimalApis.Lib 15 | @using BlazorMinimalApis.Lib.Views 16 | @using BlazorMinimalApis.Lib.Helpers -------------------------------------------------------------------------------- /Samples/BlazorMinimalApi.Pages/Program.cs: -------------------------------------------------------------------------------- 1 | using BlazorMinimalApis.Lib.Session; 2 | using BlazorMinimalApis.Pages.Lib; 3 | 4 | var builder = WebApplication.CreateBuilder(args); 5 | 6 | // Add services to the container. 7 | builder.Services.AddRazorComponents(); 8 | builder.Services.AddHttpContextAccessor(); 9 | builder.Services.AddDistributedMemoryCache(); 10 | builder.Services.AddAntiforgery(); 11 | builder.Services.AddTransient(); 12 | builder.Services.AddHttpContextAccessor(); 13 | builder.Services.AddSession(options => { 14 | options.Cookie.Name = ".blazorminimalapi.pages"; 15 | options.IdleTimeout = TimeSpan.FromMinutes(1); 16 | }); 17 | //builder.Services.AddAuthentication(); 18 | //builder.Services.AddAuthorization(new string[] { "Admin", "User" }); 19 | 20 | var app = builder.Build(); 21 | 22 | // Configure the HTTP request pipeline. 23 | if (!app.Environment.IsDevelopment()) 24 | { 25 | app.UseExceptionHandler("/Error"); 26 | // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. 27 | app.UseHsts(); 28 | } 29 | 30 | app.UseHttpsRedirection(); 31 | app.UseStaticFiles(); 32 | app.UseSession(); 33 | app.UseAntiforgery(); 34 | 35 | app.RegisterRoutes(); 36 | 37 | app.Run(); -------------------------------------------------------------------------------- /Samples/BlazorMinimalApi.Pages/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:52749", 8 | "sslPort": 44305 9 | } 10 | }, 11 | "profiles": { 12 | "http": { 13 | "commandName": "Project", 14 | "dotnetRunMessages": true, 15 | "launchBrowser": true, 16 | "applicationUrl": "http://localhost:5194", 17 | "environmentVariables": { 18 | "ASPNETCORE_ENVIRONMENT": "Development" 19 | } 20 | }, 21 | "https": { 22 | "commandName": "Project", 23 | "dotnetRunMessages": true, 24 | "launchBrowser": true, 25 | "applicationUrl": "https://localhost:7063;http://localhost:5194", 26 | "environmentVariables": { 27 | "ASPNETCORE_ENVIRONMENT": "Development" 28 | } 29 | }, 30 | "IIS Express": { 31 | "commandName": "IISExpress", 32 | "launchBrowser": true, 33 | "environmentVariables": { 34 | "ASPNETCORE_ENVIRONMENT": "Development" 35 | } 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Samples/BlazorMinimalApi.Pages/Routes/Api.cs: -------------------------------------------------------------------------------- 1 | using BlazorMinimalApis.Pages.Lib; 2 | using BlazorMinimalApis.Pages.Pages.Api.Contacts; 3 | 4 | namespace BlazorMinimalApis.Pages.Routes; 5 | 6 | public class Api : IRouteDefinition 7 | { 8 | public void Map(WebApplication app) 9 | { 10 | app.MapGet("/api/contacts", new ListContacts().Get); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Samples/BlazorMinimalApi.Pages/Routes/Web.cs: -------------------------------------------------------------------------------- 1 | using BlazorMinimalApis.Pages.Lib; 2 | using BlazorMinimalApis.Pages.Pages.Contacts; 3 | using BlazorMinimalApis.Pages.Pages.Home; 4 | using static System.Formats.Asn1.AsnWriter; 5 | 6 | namespace BlazorMinimalApis.Pages.Routes; 7 | 8 | public class Web : IRouteDefinition 9 | { 10 | public void Map(WebApplication app) 11 | { 12 | #region Home 13 | 14 | app.MapGet("/", new Home().Get); 15 | 16 | app.MapGet("/random-number", new Home().RandomNumber); 17 | 18 | #endregion 19 | 20 | #region Contacts 21 | 22 | app.MapGet("/contacts", new ListContacts().Get) 23 | .WithName("ListContacts.Get"); 24 | 25 | app.MapGet("/contacts/search", new ListContacts().GetSearch) 26 | .WithName("SearchContacts.Get"); 27 | 28 | app.MapGet("/contacts/create", new CreateContact().Get) 29 | .WithName("CreateContact.Get"); 30 | 31 | app.MapPost("/contacts/create", new CreateContact().Post) 32 | .WithName("CreateContact.Post"); 33 | 34 | app.MapGet("/contacts/{id:int}/edit", new EditContact().Get) 35 | .WithName("EditContact.Get"); 36 | 37 | app.MapPost("/contacts/{id:int}/edit", new EditContact().Post) 38 | .WithName("EditContact.Post"); 39 | 40 | app.MapGet("/contacts/{id}/delete", new DeleteContact().Get) 41 | .WithName("DeleteContact.Get"); 42 | 43 | #endregion 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Samples/BlazorMinimalApi.Pages/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | }, 8 | "AllowedHosts": "*" 9 | } 10 | -------------------------------------------------------------------------------- /Samples/BlazorMinimalApi.Pages/wwwroot/app.css: -------------------------------------------------------------------------------- 1 | html, body { 2 | font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; 3 | } 4 | 5 | h1:focus { 6 | outline: none; 7 | } 8 | 9 | a, .btn-link { 10 | color: #0071c1; 11 | } 12 | 13 | .btn-primary { 14 | color: #fff; 15 | background-color: #1b6ec2; 16 | border-color: #1861ac; 17 | } 18 | 19 | .btn:focus, .btn:active:focus, .btn-link.nav-link:focus, .form-control:focus, .form-check-input:focus { 20 | box-shadow: 0 0 0 0.1rem white, 0 0 0 0.25rem #258cfb; 21 | } 22 | 23 | .content { 24 | padding-top: 1.1rem; 25 | } 26 | 27 | .valid.modified:not([type=checkbox]) { 28 | outline: 1px solid #26b050; 29 | } 30 | 31 | .invalid { 32 | outline: 1px solid red; 33 | } 34 | 35 | .validation-message { 36 | color: red; 37 | } 38 | 39 | .blazor-error-boundary { 40 | background: url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNTYiIGhlaWdodD0iNDkiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIG92ZXJmbG93PSJoaWRkZW4iPjxkZWZzPjxjbGlwUGF0aCBpZD0iY2xpcDAiPjxyZWN0IHg9IjIzNSIgeT0iNTEiIHdpZHRoPSI1NiIgaGVpZ2h0PSI0OSIvPjwvY2xpcFBhdGg+PC9kZWZzPjxnIGNsaXAtcGF0aD0idXJsKCNjbGlwMCkiIHRyYW5zZm9ybT0idHJhbnNsYXRlKC0yMzUgLTUxKSI+PHBhdGggZD0iTTI2My41MDYgNTFDMjY0LjcxNyA1MSAyNjUuODEzIDUxLjQ4MzcgMjY2LjYwNiA1Mi4yNjU4TDI2Ny4wNTIgNTIuNzk4NyAyNjcuNTM5IDUzLjYyODMgMjkwLjE4NSA5Mi4xODMxIDI5MC41NDUgOTIuNzk1IDI5MC42NTYgOTIuOTk2QzI5MC44NzcgOTMuNTEzIDI5MSA5NC4wODE1IDI5MSA5NC42NzgyIDI5MSA5Ny4wNjUxIDI4OS4wMzggOTkgMjg2LjYxNyA5OUwyNDAuMzgzIDk5QzIzNy45NjMgOTkgMjM2IDk3LjA2NTEgMjM2IDk0LjY3ODIgMjM2IDk0LjM3OTkgMjM2LjAzMSA5NC4wODg2IDIzNi4wODkgOTMuODA3MkwyMzYuMzM4IDkzLjAxNjIgMjM2Ljg1OCA5Mi4xMzE0IDI1OS40NzMgNTMuNjI5NCAyNTkuOTYxIDUyLjc5ODUgMjYwLjQwNyA1Mi4yNjU4QzI2MS4yIDUxLjQ4MzcgMjYyLjI5NiA1MSAyNjMuNTA2IDUxWk0yNjMuNTg2IDY2LjAxODNDMjYwLjczNyA2Ni4wMTgzIDI1OS4zMTMgNjcuMTI0NSAyNTkuMzEzIDY5LjMzNyAyNTkuMzEzIDY5LjYxMDIgMjU5LjMzMiA2OS44NjA4IDI1OS4zNzEgNzAuMDg4N0wyNjEuNzk1IDg0LjAxNjEgMjY1LjM4IDg0LjAxNjEgMjY3LjgyMSA2OS43NDc1QzI2Ny44NiA2OS43MzA5IDI2Ny44NzkgNjkuNTg3NyAyNjcuODc5IDY5LjMxNzkgMjY3Ljg3OSA2Ny4xMTgyIDI2Ni40NDggNjYuMDE4MyAyNjMuNTg2IDY2LjAxODNaTTI2My41NzYgODYuMDU0N0MyNjEuMDQ5IDg2LjA1NDcgMjU5Ljc4NiA4Ny4zMDA1IDI1OS43ODYgODkuNzkyMSAyNTkuNzg2IDkyLjI4MzcgMjYxLjA0OSA5My41Mjk1IDI2My41NzYgOTMuNTI5NSAyNjYuMTE2IDkzLjUyOTUgMjY3LjM4NyA5Mi4yODM3IDI2Ny4zODcgODkuNzkyMSAyNjcuMzg3IDg3LjMwMDUgMjY2LjExNiA4Ni4wNTQ3IDI2My41NzYgODYuMDU0N1oiIGZpbGw9IiNGRkU1MDAiIGZpbGwtcnVsZT0iZXZlbm9kZCIvPjwvZz48L3N2Zz4=) no-repeat 1rem/1.8rem, #b32121; 41 | padding: 1rem 1rem 1rem 3.7rem; 42 | color: white; 43 | } 44 | 45 | .blazor-error-boundary::after { 46 | content: "An error has occurred." 47 | } 48 | -------------------------------------------------------------------------------- /Samples/BlazorMinimalApi.Pages/wwwroot/favicon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/westonwalker/BlazorMinimalAPI/c45313426c7398f5440a9b2e022d2a99549381bd/Samples/BlazorMinimalApi.Pages/wwwroot/favicon.png -------------------------------------------------------------------------------- /Samples/BlazorMinimalApi.Slices/Applications/Common/Components/FlashMessages.razor: -------------------------------------------------------------------------------- 1 | @inherits XComponent 2 | 3 | @if (Session().HasKey("success")) 4 | { 5 |
6 | @Session().GetFlash("success") 7 |
8 | } -------------------------------------------------------------------------------- /Samples/BlazorMinimalApi.Slices/Applications/Common/Layouts/MainLayout.razor: -------------------------------------------------------------------------------- 1 | @inherits LayoutComponentBase 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 |
20 |
21 |

Contact Manager

22 |

John Doe

23 |
24 |
25 |
26 |
27 | @Body 28 |
29 |
30 |
31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /Samples/BlazorMinimalApi.Slices/Applications/Contacts/Handlers/CreateContact.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | using BlazorMinimalApis.Slices.Data; 3 | using BlazorMinimalApis.Lib.Routing; 4 | using BlazorMinimalApis.Lib.Session; 5 | using BlazorMinimalApis.Slices.Applications.Contacts.Mappers; 6 | using BlazorMinimalApis.Slices.Applications.Contacts.Models; 7 | using Microsoft.AspNetCore.Mvc; 8 | using Riok.Mapperly.Abstractions; 9 | using BlazorMinimalApis.Slices.Applications.Contacts.Views; 10 | 11 | namespace BlazorMinimalApis.Slices.Applications.Contacts.Handlers; 12 | 13 | public class CreateContact : XHandler 14 | { 15 | public IResult Create() 16 | { 17 | var model = new { Form = new CreateContactForm() }; 18 | return View(model); 19 | } 20 | 21 | public IResult Store([FromForm] CreateContactForm form, SessionManager Session) 22 | { 23 | if (Validate(form).HasErrors) 24 | { 25 | var model = new { Form = form }; 26 | return View(model); 27 | } 28 | var newContact = new ContactMapper().CreateContactFormToContact(form); 29 | newContact.Id = Database.Contacts.Count() + 1; 30 | Database.Contacts.Add(newContact); 31 | 32 | Session.SetFlash("success", "Contact successfully added."); 33 | 34 | return Redirect("/contacts/create"); 35 | } 36 | } -------------------------------------------------------------------------------- /Samples/BlazorMinimalApi.Slices/Applications/Contacts/Handlers/DeleteContact.cs: -------------------------------------------------------------------------------- 1 | using BlazorMinimalApis.Slices.Data; 2 | using BlazorMinimalApis.Lib.Routing; 3 | using BlazorMinimalApis.Slices.Lib; 4 | 5 | namespace BlazorMinimalApis.Slices.Applications.Contacts.Handlers; 6 | 7 | public class DeleteContact : XHandler 8 | { 9 | public IResult Delete(int id) 10 | { 11 | var contact = Database.Contacts.First(x => x.Id == id); 12 | Database.Contacts.Remove(contact); 13 | return Redirect($"/contacts"); 14 | } 15 | } -------------------------------------------------------------------------------- /Samples/BlazorMinimalApi.Slices/Applications/Contacts/Handlers/EditContact.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | using BlazorMinimalApis.Slices.Data; 3 | using BlazorMinimalApis.Lib.Routing; 4 | using BlazorMinimalApis.Slices.Lib; 5 | using Microsoft.AspNetCore.Mvc; 6 | using Riok.Mapperly.Abstractions; 7 | using BlazorMinimalApis.Slices.Applications.Contacts.Views; 8 | using BlazorMinimalApis.Slices.Applications.Contacts.Mappers; 9 | using BlazorMinimalApis.Slices.Applications.Contacts.Models; 10 | 11 | namespace BlazorMinimalApis.Slices.Applications.Contacts.Handlers; 12 | 13 | public class EditContact : XHandler 14 | { 15 | 16 | public IResult Edit(int id) 17 | { 18 | var record = Database.Contacts.Where(x => x.Id == id).First(); 19 | var form = new ContactMapper().ContactToEditContactForm(record); 20 | var model = new { Form = form }; 21 | return View(model); 22 | } 23 | 24 | public IResult Update(int id, [FromForm] EditContactForm form) 25 | { 26 | var validation = Validate(form); 27 | if (validation.HasErrors) 28 | { 29 | var model = new { Form = form }; 30 | return View(model); 31 | } 32 | var oldContact = Database.Contacts.First(x => x.Id == id); 33 | var newContact = new ContactMapper().EditContactFormToContact(form); 34 | newContact.Id = oldContact.Id; 35 | Database.Contacts.Add(newContact); 36 | Database.Contacts.Remove(oldContact); 37 | 38 | return Redirect($"/contacts/{newContact.Id}/edit"); 39 | } 40 | } -------------------------------------------------------------------------------- /Samples/BlazorMinimalApi.Slices/Applications/Contacts/Handlers/ListContacts.cs: -------------------------------------------------------------------------------- 1 | using BlazorMinimalApis.Slices.Data; 2 | using BlazorMinimalApis.Lib.Routing; 3 | using BlazorMinimalApis.Slices.Lib; 4 | using BlazorMinimalApis.Slices.Applications.Contacts.Views; 5 | 6 | namespace BlazorMinimalApis.Slices.Applications.Contacts.Handlers; 7 | 8 | public class ListContacts : XHandler 9 | { 10 | 11 | public IResult List(HttpContext context) 12 | { 13 | var parameters = new { Database.Contacts }; 14 | return View(parameters); 15 | } 16 | } -------------------------------------------------------------------------------- /Samples/BlazorMinimalApi.Slices/Applications/Contacts/Handlers/ListContactsApi.cs: -------------------------------------------------------------------------------- 1 | using BlazorMinimalApis.Slices.Data; 2 | using BlazorMinimalApis.Lib.Routing; 3 | 4 | namespace BlazorMinimalApis.Slices.Applications.Contacts.Handlers; 5 | 6 | public class ListContactsApi : XHandler 7 | { 8 | public IResult List() 9 | { 10 | var data = new { Contacts = Database.Contacts }; 11 | return Results.Ok(data); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Samples/BlazorMinimalApi.Slices/Applications/Contacts/Handlers/SearchContacts.cs: -------------------------------------------------------------------------------- 1 | using BlazorMinimalApis.Slices.Data; 2 | using BlazorMinimalApis.Lib.Routing; 3 | using BlazorMinimalApis.Slices.Lib; 4 | using Microsoft.AspNetCore.Mvc; 5 | using BlazorMinimalApis.Slices.Applications.Contacts.Views; 6 | 7 | namespace BlazorMinimalApis.Slices.Applications.Contacts.Handlers; 8 | 9 | public class SearchContacts : XHandler 10 | { 11 | public IResult Search([FromQuery] string ContactSearch) 12 | { 13 | var contacts = Database.Contacts 14 | .Where(x => x.Name.Contains(ContactSearch, StringComparison.OrdinalIgnoreCase)) 15 | .ToList(); 16 | var model = new { Contacts = contacts }; 17 | return View(model); 18 | } 19 | } -------------------------------------------------------------------------------- /Samples/BlazorMinimalApi.Slices/Applications/Contacts/Mappers/ContactMapper.cs: -------------------------------------------------------------------------------- 1 | using BlazorMinimalApis.Slices.Applications.Contacts.Models; 2 | using BlazorMinimalApis.Slices.Data; 3 | using Riok.Mapperly.Abstractions; 4 | 5 | namespace BlazorMinimalApis.Slices.Applications.Contacts.Mappers; 6 | 7 | [Mapper] 8 | public partial class ContactMapper 9 | { 10 | public partial CreateContactForm ContactToCreateContactForm(Contact contact); 11 | public partial Contact CreateContactFormToContact(CreateContactForm contact); 12 | 13 | public partial EditContactForm ContactToEditContactForm(Contact contact); 14 | public partial Contact EditContactFormToContact(EditContactForm contact); 15 | } -------------------------------------------------------------------------------- /Samples/BlazorMinimalApi.Slices/Applications/Contacts/Models/CreateContactForm.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | 3 | namespace BlazorMinimalApis.Slices.Applications.Contacts.Models; 4 | 5 | public class CreateContactForm 6 | { 7 | [Required] public string Name { get; set; } 8 | [Required, EmailAddress] public string Email { get; set; } 9 | [Required] public string City { get; set; } 10 | [Required, Phone] public string Phone { get; set; } 11 | } 12 | -------------------------------------------------------------------------------- /Samples/BlazorMinimalApi.Slices/Applications/Contacts/Models/EditContactForm.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | 3 | namespace BlazorMinimalApis.Slices.Applications.Contacts.Models; 4 | 5 | public class EditContactForm 6 | { 7 | public int Id { get; set; } 8 | [Required] public string Name { get; set; } 9 | [Required, EmailAddress] public string Email { get; set; } 10 | [Required] public string City { get; set; } 11 | [Required, Phone] public string Phone { get; set; } 12 | } 13 | -------------------------------------------------------------------------------- /Samples/BlazorMinimalApi.Slices/Applications/Contacts/Routes.cs: -------------------------------------------------------------------------------- 1 | using BlazorMinimalApis.Slices.Applications.Contacts.Handlers; 2 | using BlazorMinimalApis.Slices.Lib; 3 | 4 | namespace BlazorMinimalApis.Slices.Applications.Contacts; 5 | 6 | public class Routes : IRouteDefinition 7 | { 8 | public void Map(WebApplication app) 9 | { 10 | // UI routes 11 | app.MapGet("/contacts", new ListContacts().List) 12 | .WithName("Contacts"); 13 | 14 | app.MapGet("/contacts/create", new CreateContact().Create) 15 | .WithName("Contacts.Create"); 16 | 17 | app.MapPost("/contacts/create", new CreateContact().Store) 18 | .WithName("Contacts.Store"); 19 | 20 | app.MapGet("/contacts/{id:int}/edit", new EditContact().Edit) 21 | .WithName("Contacts.Edit"); 22 | 23 | app.MapPost("/contacts/{id:int}/edit", new EditContact().Update) 24 | .WithName("Contacts.Update"); 25 | 26 | app.MapGet("/contacts/{id}/delete", new DeleteContact().Delete) 27 | .WithName("Contacts.Delete"); 28 | 29 | app.MapGet("/contacts/search", new SearchContacts().Search) 30 | .WithName("Contacts.Search"); 31 | 32 | // API routes 33 | app.MapGet("/api/contacts", new ListContactsApi().List); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Samples/BlazorMinimalApi.Slices/Applications/Contacts/Views/ContactsTable.razor: -------------------------------------------------------------------------------- 1 | @inherits XComponent 2 | @code { 3 | [Parameter] public List Contacts { get; set; } = new(); 4 | } 5 | 6 |
7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | @if (Contacts.Count <= 0) 15 | { 16 | 17 | 18 | 19 | } 20 | @foreach (var contact in Contacts) 21 | { 22 | 23 | 28 | 33 | 38 | 43 | 44 | } 45 |
NameEmailCityPhone
No contacts with that name found.
24 | 25 | @contact.Name 26 | 27 | 29 | 30 | @contact.Email 31 | 32 | 34 | 35 | @contact.City 36 | 37 | 39 | 40 | @contact.Phone 41 | 42 |
46 |
47 | -------------------------------------------------------------------------------- /Samples/BlazorMinimalApi.Slices/Applications/Contacts/Views/Create.razor: -------------------------------------------------------------------------------- 1 | @inherits XComponent 2 | @code { 3 | [Parameter] 4 | public CreateContactForm Form { get; set; } = new(); 5 | } 6 | 7 | Add contacts 8 | 9 | 10 |

11 | 12 | 13 | Contacts 14 | 15 | 16 | / 17 | Create 18 |

19 | 20 | 21 | 22 |
23 |
24 |
25 |
26 | 27 | 28 | @if (HasError(() => Form.Name)) 29 | { 30 |
@Message
31 | } 32 |
33 |
34 | 35 | 36 | @if (HasError(() => Form.Email)) 37 | { 38 |
@Message
39 | } 40 |
41 |
42 | 43 | 44 | @if (HasError(() => Form.City)) 45 | { 46 |
@Message
47 | } 48 |
49 |
50 | 51 | 52 | @if (HasError(() => Form.Phone)) 53 | { 54 |
@Message
55 | } 56 |
57 |
58 |
59 | 62 |
63 | 64 | 65 |
66 |
-------------------------------------------------------------------------------- /Samples/BlazorMinimalApi.Slices/Applications/Contacts/Views/Edit.razor: -------------------------------------------------------------------------------- 1 | @inherits XComponent 2 | @code { 3 | [Parameter] 4 | public EditContactForm Form { get; set; } = new(); 5 | } 6 | 7 | Edit contacts 8 | 9 | 10 |

11 | Contacts 12 | / 13 | @Form.Name 14 |

15 |
16 |
17 |
18 |
19 | 20 | 21 |
22 |
23 | 24 | 25 | @if (HasError(() => Form.Email)) 26 | { 27 |
@Message
28 | } 29 |
30 |
31 | 32 | 33 | @if (HasError(() => Form.City)) 34 | { 35 |
@Message
36 | } 37 |
38 |
39 | 40 | 41 | @if (HasError(() => Form.Phone)) 42 | { 43 |
@Message
44 | } 45 |
46 |
47 |
48 | Delete Contact 49 | 52 |
53 | 54 | 55 |
56 |
-------------------------------------------------------------------------------- /Samples/BlazorMinimalApi.Slices/Applications/Contacts/Views/List.razor: -------------------------------------------------------------------------------- 1 | @inherits XComponent 2 | @code { 3 | [Parameter] 4 | public List Contacts { get; set; } = new(); 5 | } 6 | 7 | Contacts 8 | 9 | 10 |

11 | Contacts 12 |

13 |
14 |
15 | 16 |
17 | Add contact 18 |
19 | 20 |
21 |
22 | 23 |
24 |
25 |
26 | -------------------------------------------------------------------------------- /Samples/BlazorMinimalApi.Slices/Applications/Contacts/Views/_Imports.razor: -------------------------------------------------------------------------------- 1 | @using BlazorMinimalApis.Slices.Applications.Contacts 2 | @using BlazorMinimalApis.Slices.Applications.Contacts.Models 3 | -------------------------------------------------------------------------------- /Samples/BlazorMinimalApi.Slices/Applications/Home/Handlers/ShowHome.cs: -------------------------------------------------------------------------------- 1 | using BlazorMinimalApis.Slices.Data; 2 | using BlazorMinimalApis.Lib.Routing; 3 | using BlazorMinimalApis.Slices.Lib; 4 | using Microsoft.AspNetCore.Mvc; 5 | using BlazorMinimalApis.Slices.Applications.Home.Views; 6 | 7 | namespace BlazorMinimalApis.Slices.Applications.Home.Handlers; 8 | 9 | public class ShowHome : XHandler 10 | { 11 | public IResult Show() 12 | { 13 | return View(); 14 | } 15 | 16 | public IResult RandomNumber() 17 | { 18 | Random rnd = new Random(); 19 | var num = rnd.Next(); 20 | return View<_RandomNumber>(new { Num = num }); 21 | } 22 | } -------------------------------------------------------------------------------- /Samples/BlazorMinimalApi.Slices/Applications/Home/Routes.cs: -------------------------------------------------------------------------------- 1 | using BlazorMinimalApis.Slices.Applications.Home.Handlers; 2 | using BlazorMinimalApis.Slices.Lib; 3 | 4 | namespace BlazorMinimalApis.Slices.Applications.Home; 5 | 6 | public class Routes : IRouteDefinition 7 | { 8 | public void Map(WebApplication app) 9 | { 10 | app.MapGet("/", new ShowHome().Show); 11 | 12 | app.MapGet("/random-number", new ShowHome().RandomNumber); 13 | 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Samples/BlazorMinimalApi.Slices/Applications/Home/Views/Show.razor: -------------------------------------------------------------------------------- 1 | @inherits XComponent 2 | 3 | Home 4 | 5 | 6 |
7 |

8 | Welcome to the contact manager 9 |

10 |

This is a demo on how to use Minimal APIs + Razor Components + HTMX to create dynamic server side rendered apps.

11 | Explore the crud example 12 |

13 | You can check out the repo here 14 |

15 |

16 | Using Minimal APIs and Razor components is possible because of a new class in .NET 8: RazorComponentResult 17 |

18 |

This returns an IResult after initializing a Razor component, making it possible to use Razor components in Minimal APIs.

19 |

20 | Requirements 21 |

22 |

23 | Requires .NET 8 RC1 installed. 24 |

25 |

26 | Partial page reload on navigation with hx-boost 27 |

28 |

29 | The HTMX attribute hx-boost turns internal links into ajax calls. This speeds up site speed since there are no full page reloads. You can opt in and out of this behavior on a link by link basis. 30 |

31 |

32 | This app uses hx-boost on the body tag, turning on this functionality for all links. 33 |

34 |

35 | Get and Post requests with hx-get and hx-post 36 |

37 |

38 | The HTMX attributes hx-get and hx-post sets up ajax calls to endpoints and swaps html on the page with what was returned. 39 |

40 |

41 | This is useful for submitting forms, searching tables, and modifying the dom from a user interaction on the page. 42 |

43 |

44 | Polling 45 |

46 |

47 | The HTMX attribute hx-trigger can be used to poll the server. This can setup ajax calls to endpoints at an interval and swap html on the page with what was returned. 48 |

49 |

50 | Below is random number generator. 51 |

52 |
53 |
54 | 55 |
56 |
57 |

58 | HTMX calls /random-number every 2s and replaces the html with the html returned by the endpoint. 59 |

60 |
61 |
-------------------------------------------------------------------------------- /Samples/BlazorMinimalApi.Slices/Applications/Home/Views/_RandomNumber.razor: -------------------------------------------------------------------------------- 1 | @code { 2 | [Parameter] public int Num { get; set; } 3 | } 4 | 5 |

Random Number is @Num

6 | -------------------------------------------------------------------------------- /Samples/BlazorMinimalApi.Slices/Applications/_Imports.razor: -------------------------------------------------------------------------------- 1 | @using System.Net.Http 2 | @using System.Net.Http.Json 3 | @using Microsoft.AspNetCore.Components.Forms 4 | @using Microsoft.AspNetCore.Components.Routing 5 | @using Microsoft.AspNetCore.Components.Web 6 | @using Microsoft.AspNetCore.Components.Web.Virtualization 7 | @using Microsoft.JSInterop 8 | @using Microsoft.AspNetCore.Authorization 9 | @using BlazorMinimalApis 10 | @using BlazorMinimalApis.Slices 11 | @using BlazorMinimalApis.Slices.Applications.Common.Layouts 12 | @using BlazorMinimalApis.Slices.Applications.Common.Components 13 | @using BlazorMinimalApis.Slices.Data 14 | @using BlazorMinimalApis.Lib 15 | @using BlazorMinimalApis.Lib.Views 16 | @using BlazorMinimalApis.Lib.Helpers -------------------------------------------------------------------------------- /Samples/BlazorMinimalApi.Slices/BlazorMinimalApi.Slices.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net8.0 5 | enable 6 | enable 7 | BlazorMinimalApis.Slices 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | <_ContentIncludedByDefault Remove="Lib\Views\EmptyLayout.razor" /> 16 | <_ContentIncludedByDefault Remove="Lib\Views\PageComponent.razor" /> 17 | <_ContentIncludedByDefault Remove="Lib\Views\XLayout.razor" /> 18 | <_ContentIncludedByDefault Remove="Endpoints\Pages\Contacts\ContactsSearchTable.razor" /> 19 | <_ContentIncludedByDefault Remove="Endpoints\Pages\Contacts\Create.razor" /> 20 | <_ContentIncludedByDefault Remove="Endpoints\Pages\Contacts\Edit.razor" /> 21 | <_ContentIncludedByDefault Remove="Endpoints\Pages\Contacts\List.razor" /> 22 | <_ContentIncludedByDefault Remove="Endpoints\Pages\Home\Home.razor" /> 23 | <_ContentIncludedByDefault Remove="Endpoints\Pages\Home\RandomNumber.razor" /> 24 | <_ContentIncludedByDefault Remove="Endpoints\Pages\Shared\FlashMessages.razor" /> 25 | <_ContentIncludedByDefault Remove="Endpoints\Pages\Shared\Layout\MainLayout.razor" /> 26 | <_ContentIncludedByDefault Remove="Endpoints\Pages\_Imports.razor" /> 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /Samples/BlazorMinimalApi.Slices/Data/Database.cs: -------------------------------------------------------------------------------- 1 | namespace BlazorMinimalApis.Slices.Data; 2 | 3 | public static class Database 4 | { 5 | public static List Contacts = new() 6 | { 7 | new Contact { Id = 1, Name = "Kramer", Email = "kramer@gmail.com", City = "New York", Phone = "3927374545" }, 8 | new Contact { Id = 2, Name = "Jerry", Email = "Jerry@gmail.com", City = "Queens", Phone = "3954563237" } 9 | }; 10 | 11 | } 12 | 13 | public class Contact 14 | { 15 | public int Id { get; set; } 16 | public string Name { get; set; } 17 | public string Email { get; set; } 18 | public string City { get; set; } 19 | public string Phone { get; set; } 20 | } -------------------------------------------------------------------------------- /Samples/BlazorMinimalApi.Slices/Lib/IRouteDefinition.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Builder; 2 | 3 | namespace BlazorMinimalApis.Slices.Lib; 4 | 5 | public interface IRouteDefinition 6 | { 7 | void Map(WebApplication app); 8 | } -------------------------------------------------------------------------------- /Samples/BlazorMinimalApi.Slices/Lib/RegisterRoutesExtension.cs: -------------------------------------------------------------------------------- 1 | using BlazorMinimalApis.Lib.Routing; 2 | using Microsoft.AspNetCore.Builder; 3 | 4 | namespace BlazorMinimalApis.Slices.Lib; 5 | 6 | public static class RegisterRoutesExtension 7 | { 8 | public static void RegisterRoutes(this WebApplication app) 9 | { 10 | var endpointDefinitions = typeof(Program).Assembly 11 | .GetTypes() 12 | .Where(t => t.IsAssignableTo(typeof(IRouteDefinition)) 13 | && !t.IsAbstract && !t.IsInterface) 14 | .Select(Activator.CreateInstance) 15 | .Cast(); 16 | 17 | foreach (var endpointDef in endpointDefinitions) 18 | { 19 | endpointDef.Map(app); 20 | } 21 | } 22 | } -------------------------------------------------------------------------------- /Samples/BlazorMinimalApi.Slices/Program.cs: -------------------------------------------------------------------------------- 1 | using BlazorMinimalApis.Lib.Session; 2 | using BlazorMinimalApis.Slices.Lib; 3 | 4 | var builder = WebApplication.CreateBuilder(args); 5 | 6 | // Add services to the container. 7 | builder.Services.AddRazorComponents(); 8 | builder.Services.AddHttpContextAccessor(); 9 | builder.Services.AddDistributedMemoryCache(); 10 | builder.Services.AddAntiforgery(); 11 | builder.Services.AddTransient(); 12 | builder.Services.AddHttpContextAccessor(); 13 | builder.Services.AddSession(options => { 14 | options.Cookie.Name = ".blazorminimalapi.pages"; 15 | options.IdleTimeout = TimeSpan.FromMinutes(1); 16 | }); 17 | //builder.Services.AddAuthentication(); 18 | //builder.Services.AddAuthorization(new string[] { "Admin", "User" }); 19 | 20 | var app = builder.Build(); 21 | 22 | // Configure the HTTP request pipeline. 23 | if (!app.Environment.IsDevelopment()) 24 | { 25 | app.UseExceptionHandler("/Error"); 26 | // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. 27 | app.UseHsts(); 28 | } 29 | 30 | app.UseHttpsRedirection(); 31 | app.UseStaticFiles(); 32 | app.UseSession(); 33 | app.UseAntiforgery(); 34 | 35 | app.RegisterRoutes(); 36 | 37 | app.Run(); -------------------------------------------------------------------------------- /Samples/BlazorMinimalApi.Slices/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:52749", 8 | "sslPort": 44305 9 | } 10 | }, 11 | "profiles": { 12 | "http": { 13 | "commandName": "Project", 14 | "dotnetRunMessages": true, 15 | "launchBrowser": true, 16 | "applicationUrl": "http://localhost:5194", 17 | "environmentVariables": { 18 | "ASPNETCORE_ENVIRONMENT": "Development" 19 | } 20 | }, 21 | "https": { 22 | "commandName": "Project", 23 | "dotnetRunMessages": true, 24 | "launchBrowser": true, 25 | "applicationUrl": "https://localhost:7063;http://localhost:5194", 26 | "environmentVariables": { 27 | "ASPNETCORE_ENVIRONMENT": "Development" 28 | } 29 | }, 30 | "IIS Express": { 31 | "commandName": "IISExpress", 32 | "launchBrowser": true, 33 | "environmentVariables": { 34 | "ASPNETCORE_ENVIRONMENT": "Development" 35 | } 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Samples/BlazorMinimalApi.Slices/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | }, 8 | "AllowedHosts": "*" 9 | } 10 | -------------------------------------------------------------------------------- /Samples/BlazorMinimalApi.Slices/wwwroot/app.css: -------------------------------------------------------------------------------- 1 | html, body { 2 | font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; 3 | } 4 | 5 | h1:focus { 6 | outline: none; 7 | } 8 | 9 | a, .btn-link { 10 | color: #0071c1; 11 | } 12 | 13 | .btn-primary { 14 | color: #fff; 15 | background-color: #1b6ec2; 16 | border-color: #1861ac; 17 | } 18 | 19 | .btn:focus, .btn:active:focus, .btn-link.nav-link:focus, .form-control:focus, .form-check-input:focus { 20 | box-shadow: 0 0 0 0.1rem white, 0 0 0 0.25rem #258cfb; 21 | } 22 | 23 | .content { 24 | padding-top: 1.1rem; 25 | } 26 | 27 | .valid.modified:not([type=checkbox]) { 28 | outline: 1px solid #26b050; 29 | } 30 | 31 | .invalid { 32 | outline: 1px solid red; 33 | } 34 | 35 | .validation-message { 36 | color: red; 37 | } 38 | 39 | .blazor-error-boundary { 40 | background: url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNTYiIGhlaWdodD0iNDkiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIG92ZXJmbG93PSJoaWRkZW4iPjxkZWZzPjxjbGlwUGF0aCBpZD0iY2xpcDAiPjxyZWN0IHg9IjIzNSIgeT0iNTEiIHdpZHRoPSI1NiIgaGVpZ2h0PSI0OSIvPjwvY2xpcFBhdGg+PC9kZWZzPjxnIGNsaXAtcGF0aD0idXJsKCNjbGlwMCkiIHRyYW5zZm9ybT0idHJhbnNsYXRlKC0yMzUgLTUxKSI+PHBhdGggZD0iTTI2My41MDYgNTFDMjY0LjcxNyA1MSAyNjUuODEzIDUxLjQ4MzcgMjY2LjYwNiA1Mi4yNjU4TDI2Ny4wNTIgNTIuNzk4NyAyNjcuNTM5IDUzLjYyODMgMjkwLjE4NSA5Mi4xODMxIDI5MC41NDUgOTIuNzk1IDI5MC42NTYgOTIuOTk2QzI5MC44NzcgOTMuNTEzIDI5MSA5NC4wODE1IDI5MSA5NC42NzgyIDI5MSA5Ny4wNjUxIDI4OS4wMzggOTkgMjg2LjYxNyA5OUwyNDAuMzgzIDk5QzIzNy45NjMgOTkgMjM2IDk3LjA2NTEgMjM2IDk0LjY3ODIgMjM2IDk0LjM3OTkgMjM2LjAzMSA5NC4wODg2IDIzNi4wODkgOTMuODA3MkwyMzYuMzM4IDkzLjAxNjIgMjM2Ljg1OCA5Mi4xMzE0IDI1OS40NzMgNTMuNjI5NCAyNTkuOTYxIDUyLjc5ODUgMjYwLjQwNyA1Mi4yNjU4QzI2MS4yIDUxLjQ4MzcgMjYyLjI5NiA1MSAyNjMuNTA2IDUxWk0yNjMuNTg2IDY2LjAxODNDMjYwLjczNyA2Ni4wMTgzIDI1OS4zMTMgNjcuMTI0NSAyNTkuMzEzIDY5LjMzNyAyNTkuMzEzIDY5LjYxMDIgMjU5LjMzMiA2OS44NjA4IDI1OS4zNzEgNzAuMDg4N0wyNjEuNzk1IDg0LjAxNjEgMjY1LjM4IDg0LjAxNjEgMjY3LjgyMSA2OS43NDc1QzI2Ny44NiA2OS43MzA5IDI2Ny44NzkgNjkuNTg3NyAyNjcuODc5IDY5LjMxNzkgMjY3Ljg3OSA2Ny4xMTgyIDI2Ni40NDggNjYuMDE4MyAyNjMuNTg2IDY2LjAxODNaTTI2My41NzYgODYuMDU0N0MyNjEuMDQ5IDg2LjA1NDcgMjU5Ljc4NiA4Ny4zMDA1IDI1OS43ODYgODkuNzkyMSAyNTkuNzg2IDkyLjI4MzcgMjYxLjA0OSA5My41Mjk1IDI2My41NzYgOTMuNTI5NSAyNjYuMTE2IDkzLjUyOTUgMjY3LjM4NyA5Mi4yODM3IDI2Ny4zODcgODkuNzkyMSAyNjcuMzg3IDg3LjMwMDUgMjY2LjExNiA4Ni4wNTQ3IDI2My41NzYgODYuMDU0N1oiIGZpbGw9IiNGRkU1MDAiIGZpbGwtcnVsZT0iZXZlbm9kZCIvPjwvZz48L3N2Zz4=) no-repeat 1rem/1.8rem, #b32121; 41 | padding: 1rem 1rem 1rem 3.7rem; 42 | color: white; 43 | } 44 | 45 | .blazor-error-boundary::after { 46 | content: "An error has occurred." 47 | } 48 | -------------------------------------------------------------------------------- /Samples/BlazorMinimalApi.Slices/wwwroot/favicon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/westonwalker/BlazorMinimalAPI/c45313426c7398f5440a9b2e022d2a99549381bd/Samples/BlazorMinimalApi.Slices/wwwroot/favicon.png -------------------------------------------------------------------------------- /Samples/BlazorMinimalApis.Mvc/BlazorMinimalApis.Mvc.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /Samples/BlazorMinimalApis.Mvc/Controllers/Api/ContactApiController.cs: -------------------------------------------------------------------------------- 1 | using BlazorMinimalApis.Lib.Routing; 2 | using BlazorMinimalApis.Mvc.Data; 3 | 4 | namespace BlazorMinimalApis.Mvc.Controllers.Api; 5 | 6 | public class ContactApiController : ApiController 7 | { 8 | public IResult List() 9 | { 10 | var data = new { Contacts = Database.Contacts }; 11 | return Results.Ok(data); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Samples/BlazorMinimalApis.Mvc/Controllers/ContactController.cs: -------------------------------------------------------------------------------- 1 | using BlazorMinimalApis.Lib.Routing; 2 | using BlazorMinimalApis.Lib.Session; 3 | using BlazorMinimalApis.Mvc.Data; 4 | using BlazorMinimalApis.Mvc.Views.Contacts; 5 | using Microsoft.AspNetCore.Http.HttpResults; 6 | using Microsoft.AspNetCore.Mvc; 7 | using Riok.Mapperly.Abstractions; 8 | using System.ComponentModel.DataAnnotations; 9 | 10 | namespace BlazorMinimalApis.Mvc.Controllers; 11 | 12 | public class ContactController : XController 13 | { 14 | public IResult List(HttpContext context) 15 | { 16 | var parameters = new { Contacts = Database.Contacts }; 17 | return View(parameters); 18 | } 19 | 20 | public IResult Search([FromQuery] string ContactSearch) 21 | { 22 | var contacts = Database.Contacts 23 | .Where(x => x.Name.Contains(ContactSearch, StringComparison.OrdinalIgnoreCase)) 24 | .ToList(); 25 | var model = new { Contacts = contacts }; 26 | return View<_ContactsTable>(model); 27 | } 28 | 29 | public IResult Create() 30 | { 31 | var model = new { Form = new CreateContactForm() }; 32 | return View(model); 33 | } 34 | 35 | public IResult Store([FromForm] CreateContactForm form, SessionManager Session) 36 | { 37 | if (Validate(form).HasErrors) 38 | { 39 | var model = new { Form = form }; 40 | return View(model); 41 | } 42 | var newContact = new CreateContactMapper().FormToContact(form); 43 | newContact.Id = Database.Contacts.Count() + 1; 44 | Database.Contacts.Add(newContact); 45 | 46 | Session.SetFlash("success", "Contact successfully added."); 47 | 48 | return Redirect("/contacts/create"); 49 | } 50 | 51 | public IResult Edit(int id) 52 | { 53 | var record = Database.Contacts.Where(x => x.Id == id).First(); 54 | var form = new EditContactMapper().ContactToForm(record); 55 | var model = new { Form = form }; 56 | return View(model); 57 | } 58 | 59 | public IResult Update(int id, [FromForm] EditContactForm form) 60 | { 61 | var validation = Validate(form); 62 | if (validation.HasErrors) 63 | { 64 | var model = new { Form = form }; 65 | return View(model); 66 | } 67 | var oldContact = Database.Contacts.First(x => x.Id == id); 68 | var newContact = new EditContactMapper().FormToContact(form); 69 | newContact.Id = oldContact.Id; 70 | Database.Contacts.Add(newContact); 71 | Database.Contacts.Remove(oldContact); 72 | 73 | return Redirect($"/contacts/{newContact.Id}/edit"); 74 | } 75 | 76 | public IResult Delete(int id) 77 | { 78 | var contact = Database.Contacts.First(x => x.Id == id); 79 | Database.Contacts.Remove(contact); 80 | return Redirect($"/contacts"); 81 | } 82 | } 83 | 84 | public class CreateContactForm 85 | { 86 | [Required] public string Name { get; set; } 87 | [Required, EmailAddress] public string Email { get; set; } 88 | [Required] public string City { get; set; } 89 | [Required, Phone] public string Phone { get; set; } 90 | } 91 | 92 | [Mapper] 93 | public partial class CreateContactMapper 94 | { 95 | public partial CreateContactForm ContactToForm(Contact contact); 96 | public partial Contact FormToContact(CreateContactForm contact); 97 | } 98 | 99 | public class EditContactForm 100 | { 101 | public int Id { get; set; } 102 | [Required] public string Name { get; set; } 103 | [Required, EmailAddress] public string Email { get; set; } 104 | [Required] public string City { get; set; } 105 | [Required, Phone] public string Phone { get; set; } 106 | } 107 | 108 | 109 | [Mapper] 110 | public partial class EditContactMapper 111 | { 112 | public partial EditContactForm ContactToForm(Contact contact); 113 | public partial Contact FormToContact(EditContactForm contact); 114 | } -------------------------------------------------------------------------------- /Samples/BlazorMinimalApis.Mvc/Controllers/HomeController.cs: -------------------------------------------------------------------------------- 1 | using BlazorMinimalApis.Lib.Routing; 2 | using BlazorMinimalApis.Mvc.Views.Home; 3 | 4 | namespace BlazorMinimalApis.Mvc.Controllers; 5 | 6 | public class HomeController : XController 7 | { 8 | public IResult Index() 9 | { 10 | return View(); 11 | } 12 | 13 | public IResult RandomNumber() 14 | { 15 | Random rnd = new Random(); 16 | var num = rnd.Next(); 17 | return View<_RandomNumber>(new { Num = num }); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Samples/BlazorMinimalApis.Mvc/Data/Database.cs: -------------------------------------------------------------------------------- 1 | namespace BlazorMinimalApis.Mvc.Data; 2 | 3 | public static class Database 4 | { 5 | public static List Contacts = new() 6 | { 7 | new Contact { Id = 1, Name = "Kramer", Email = "kramer@gmail.com", City = "New York", Phone = "3927374545" }, 8 | new Contact { Id = 2, Name = "Jerry", Email = "Jerry@gmail.com", City = "Queens", Phone = "3954563237" } 9 | }; 10 | 11 | } 12 | 13 | public class Contact 14 | { 15 | public int Id { get; set; } 16 | public string Name { get; set; } 17 | public string Email { get; set; } 18 | public string City { get; set; } 19 | public string Phone { get; set; } 20 | } 21 | -------------------------------------------------------------------------------- /Samples/BlazorMinimalApis.Mvc/Lib/IRouteDefinition.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Builder; 2 | 3 | namespace BlazorMinimalApis.Mvc.Lib; 4 | 5 | public interface IRouteDefinition 6 | { 7 | void Map(WebApplication app); 8 | } -------------------------------------------------------------------------------- /Samples/BlazorMinimalApis.Mvc/Lib/RegisterRoutesExtension.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Builder; 2 | 3 | namespace BlazorMinimalApis.Mvc.Lib; 4 | 5 | public static class RegisterRoutesExtension 6 | { 7 | public static void RegisterRoutes(this WebApplication app) 8 | { 9 | var endpointDefinitions = typeof(Program).Assembly 10 | .GetTypes() 11 | .Where(t => t.IsAssignableTo(typeof(IRouteDefinition)) 12 | && !t.IsAbstract && !t.IsInterface) 13 | .Select(Activator.CreateInstance) 14 | .Cast(); 15 | 16 | foreach (var endpointDef in endpointDefinitions) 17 | { 18 | endpointDef.Map(app); 19 | } 20 | } 21 | } -------------------------------------------------------------------------------- /Samples/BlazorMinimalApis.Mvc/Program.cs: -------------------------------------------------------------------------------- 1 | using BlazorMinimalApis.Lib.Session; 2 | using BlazorMinimalApis.Mvc.Lib; 3 | 4 | var builder = WebApplication.CreateBuilder(args); 5 | 6 | // Add services to the container. 7 | builder.Services.AddRazorComponents(); 8 | builder.Services.AddHttpContextAccessor(); 9 | builder.Services.AddDistributedMemoryCache(); 10 | builder.Services.AddAntiforgery(); 11 | builder.Services.AddTransient(); 12 | builder.Services.AddHttpContextAccessor(); 13 | builder.Services.AddSession(options => { 14 | options.Cookie.Name = ".blazorminimalapi.mvc"; 15 | options.IdleTimeout = TimeSpan.FromMinutes(1); 16 | }); 17 | //builder.Services.AddAuthentication(); 18 | //builder.Services.AddAuthorization(new string[] { "Admin", "User" }); 19 | 20 | var app = builder.Build(); 21 | 22 | // Configure the HTTP request pipeline. 23 | if (!app.Environment.IsDevelopment()) 24 | { 25 | app.UseExceptionHandler("/Error"); 26 | // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. 27 | app.UseHsts(); 28 | } 29 | 30 | app.UseHttpsRedirection(); 31 | app.UseStaticFiles(); 32 | app.UseSession(); 33 | app.UseAntiforgery(); 34 | 35 | app.RegisterRoutes(); 36 | 37 | app.Run(); -------------------------------------------------------------------------------- /Samples/BlazorMinimalApis.Mvc/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:31883", 8 | "sslPort": 44378 9 | } 10 | }, 11 | "profiles": { 12 | "http": { 13 | "commandName": "Project", 14 | "dotnetRunMessages": true, 15 | "launchBrowser": true, 16 | "applicationUrl": "http://localhost:5057", 17 | "environmentVariables": { 18 | "ASPNETCORE_ENVIRONMENT": "Development" 19 | } 20 | }, 21 | "https": { 22 | "commandName": "Project", 23 | "dotnetRunMessages": true, 24 | "launchBrowser": true, 25 | "applicationUrl": "https://localhost:7103;http://localhost:5057", 26 | "environmentVariables": { 27 | "ASPNETCORE_ENVIRONMENT": "Development" 28 | } 29 | }, 30 | "IIS Express": { 31 | "commandName": "IISExpress", 32 | "launchBrowser": true, 33 | "environmentVariables": { 34 | "ASPNETCORE_ENVIRONMENT": "Development" 35 | } 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Samples/BlazorMinimalApis.Mvc/Routes/Api.cs: -------------------------------------------------------------------------------- 1 | using BlazorMinimalApis.Mvc.Controllers.Api; 2 | using BlazorMinimalApis.Mvc.Lib; 3 | 4 | namespace BlazorMinimalApis.Mvc.Routes; 5 | 6 | public class Api : IRouteDefinition 7 | { 8 | public void Map(WebApplication app) 9 | { 10 | app.MapGet("/api/contacts", new ContactApiController().List); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Samples/BlazorMinimalApis.Mvc/Routes/Web.cs: -------------------------------------------------------------------------------- 1 | using BlazorMinimalApis.Mvc.Controllers; 2 | using BlazorMinimalApis.Mvc.Lib; 3 | using BlazorMinimalApis.Mvc.Views.Contacts; 4 | using BlazorMinimalApis.Mvc.Views.Home; 5 | using System.Collections.Generic; 6 | using static System.Formats.Asn1.AsnWriter; 7 | 8 | namespace BlazorMinimalApis.Mvc.Routes; 9 | 10 | public class Web : IRouteDefinition 11 | { 12 | public void Map(WebApplication app) 13 | { 14 | #region Home 15 | 16 | app.MapGet("/", new HomeController().Index); 17 | 18 | app.MapGet("/random-number", new HomeController().RandomNumber); 19 | 20 | #endregion 21 | 22 | #region Contacts 23 | 24 | app.MapGet("/contacts", new ContactController().List) 25 | .WithName("Contacts"); 26 | 27 | app.MapGet("/contacts/search", new ContactController().Search) 28 | .WithName("Contacts.Search"); 29 | 30 | app.MapGet("/contacts/create", new ContactController().Create) 31 | .WithName("Contacts.Create"); 32 | 33 | app.MapPost("/contacts/create", new ContactController().Store) 34 | .WithName("Contacts.Store"); 35 | 36 | app.MapGet("/contacts/{id:int}/edit", new ContactController().Edit) 37 | .WithName("Contacts.Edit"); 38 | 39 | app.MapPost("/contacts/{id:int}/edit", new ContactController().Update) 40 | .WithName("Contacts.Update"); 41 | 42 | app.MapGet("/contacts/{id}/delete", new ContactController().Delete) 43 | .WithName("Contacts.Delete"); 44 | 45 | #endregion 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Samples/BlazorMinimalApis.Mvc/Views/Components/FlashMessages.razor: -------------------------------------------------------------------------------- 1 | @inherits XComponent 2 | 3 | @if (Session().HasKey("success")) 4 | { 5 |
6 | @Session().GetFlash("success") 7 |
8 | } -------------------------------------------------------------------------------- /Samples/BlazorMinimalApis.Mvc/Views/Contacts/Create.razor: -------------------------------------------------------------------------------- 1 | @inherits XComponent 2 | @code { 3 | [Parameter] 4 | public CreateContactForm Form { get; set; } = new(); 5 | } 6 | 7 | Add contacts 8 | 9 | 10 |

11 | 12 | 13 | Contacts 14 | 15 | 16 | / 17 | Create 18 |

19 | 20 | 21 | 22 |
23 |
24 |
25 |
26 | 27 | 28 | @if (HasError(() => Form.Name)) 29 | { 30 |
@Message
31 | } 32 |
33 |
34 | 35 | 36 | @if (HasError(() => Form.Email)) 37 | { 38 |
@Message
39 | } 40 |
41 |
42 | 43 | 44 | @if (HasError(() => Form.City)) 45 | { 46 |
@Message
47 | } 48 |
49 |
50 | 51 | 52 | @if (HasError(() => Form.Phone)) 53 | { 54 |
@Message
55 | } 56 |
57 |
58 |
59 | 62 |
63 | 64 | 65 |
66 |
-------------------------------------------------------------------------------- /Samples/BlazorMinimalApis.Mvc/Views/Contacts/Edit.razor: -------------------------------------------------------------------------------- 1 | @inherits XComponent 2 | @code { 3 | [Parameter] 4 | public EditContactForm Form { get; set; } = new(); 5 | } 6 | 7 | Edit contacts 8 | 9 | 10 |

11 | Contacts 12 | / 13 | @Form.Name 14 |

15 |
16 |
17 |
18 |
19 | 20 | 21 |
22 |
23 | 24 | 25 | @if (HasError(() => Form.Email)) 26 | { 27 |
@Message
28 | } 29 |
30 |
31 | 32 | 33 | @if (HasError(() => Form.City)) 34 | { 35 |
@Message
36 | } 37 |
38 |
39 | 40 | 41 | @if (HasError(() => Form.Phone)) 42 | { 43 |
@Message
44 | } 45 |
46 |
47 |
48 | Delete Contact 49 | 52 |
53 | 54 | 55 |
56 |
-------------------------------------------------------------------------------- /Samples/BlazorMinimalApis.Mvc/Views/Contacts/List.razor: -------------------------------------------------------------------------------- 1 | @inherits XComponent 2 | @code { 3 | [Parameter] 4 | public List Contacts { get; set; } = new(); 5 | } 6 | 7 | Contacts 8 | 9 | 10 |

11 | Contacts 12 |

13 |
14 |
15 | 16 |
17 | Add contact 18 |
19 | 20 |
21 |
22 | <_ContactsTable Contacts="Contacts" /> 23 |
24 |
25 |
26 | -------------------------------------------------------------------------------- /Samples/BlazorMinimalApis.Mvc/Views/Contacts/_ContactsTable.razor: -------------------------------------------------------------------------------- 1 | @inherits XComponent 2 | @code { 3 | [Parameter] public List Contacts { get; set; } = new(); 4 | } 5 | 6 |
7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | @if (Contacts.Count <= 0) 15 | { 16 | 17 | 18 | 19 | } 20 | @foreach (var contact in Contacts) 21 | { 22 | 23 | 28 | 33 | 38 | 43 | 44 | } 45 |
NameEmailCityPhone
No contacts with that name found.
24 | 25 | @contact.Name 26 | 27 | 29 | 30 | @contact.Email 31 | 32 | 34 | 35 | @contact.City 36 | 37 | 39 | 40 | @contact.Phone 41 | 42 |
46 |
47 | -------------------------------------------------------------------------------- /Samples/BlazorMinimalApis.Mvc/Views/Home/Home.razor: -------------------------------------------------------------------------------- 1 | @inherits XComponent 2 | 3 | Home 4 | 5 | 6 |
7 |

8 | Welcome to the contact manager 9 |

10 |

This is a demo on how to use Minimal APIs + Razor Components + HTMX to create dynamic server side rendered apps.

11 | Explore the crud example 12 |

13 | You can check out the repo here 14 |

15 |

16 | Using Minimal APIs and Razor components is possible because of a new class in .NET 8: RazorComponentResult 17 |

18 |

This returns an IResult after initializing a Razor component, making it possible to use Razor components in Minimal APIs.

19 |

20 | Requirements 21 |

22 |

23 | Requires .NET 8 RC1 installed. 24 |

25 |

26 | Partial page reload on navigation with hx-boost 27 |

28 |

29 | The HTMX attribute hx-boost turns internal links into ajax calls. This speeds up site speed since there are no full page reloads. You can opt in and out of this behavior on a link by link basis. 30 |

31 |

32 | This app uses hx-boost on the body tag, turning on this functionality for all links. 33 |

34 |

35 | Get and Post requests with hx-get and hx-post 36 |

37 |

38 | The HTMX attributes hx-get and hx-post sets up ajax calls to endpoints and swaps html on the page with what was returned. 39 |

40 |

41 | This is useful for submitting forms, searching tables, and modifying the dom from a user interaction on the page. 42 |

43 |

44 | Polling 45 |

46 |

47 | The HTMX attribute hx-trigger can be used to poll the server. This can setup ajax calls to endpoints at an interval and swap html on the page with what was returned. 48 |

49 |

50 | Below is random number generator. 51 |

52 |
53 |
54 | 55 |
56 |
57 |

58 | HTMX calls /random-number every 2s and replaces the html with the html returned by the endpoint. 59 |

60 |
61 |
-------------------------------------------------------------------------------- /Samples/BlazorMinimalApis.Mvc/Views/Home/_RandomNumber.razor: -------------------------------------------------------------------------------- 1 | @code { 2 | [Parameter] public int Num { get; set; } 3 | } 4 | 5 |

Random Number is @Num

6 | -------------------------------------------------------------------------------- /Samples/BlazorMinimalApis.Mvc/Views/Layouts/MainLayout.razor: -------------------------------------------------------------------------------- 1 | @inherits LayoutComponentBase 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 |
20 |
21 |

Contact Manager

22 |

John Doe

23 |
24 |
25 |
26 |
27 | @Body 28 |
29 |
30 |
31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /Samples/BlazorMinimalApis.Mvc/Views/_Imports.razor: -------------------------------------------------------------------------------- 1 | @using System.Net.Http 2 | @using System.Net.Http.Json 3 | @using Microsoft.AspNetCore.Components.Forms 4 | @using Microsoft.AspNetCore.Components.Routing 5 | @using Microsoft.AspNetCore.Components.Web 6 | @using Microsoft.AspNetCore.Components.Web.Virtualization 7 | @using Microsoft.JSInterop 8 | @using Microsoft.AspNetCore.Authorization 9 | @using BlazorMinimalApis 10 | @using BlazorMinimalApis.Lib 11 | @using BlazorMinimalApis.Lib.Views 12 | @using BlazorMinimalApis.Lib.Helpers 13 | @using BlazorMinimalApis.Mvc.Data 14 | @using BlazorMinimalApis.Mvc.Controllers 15 | @using BlazorMinimalApis.Mvc.Views 16 | @using BlazorMinimalApis.Mvc.Views.Layouts 17 | @using BlazorMinimalApis.Mvc.Views.Components -------------------------------------------------------------------------------- /Samples/BlazorMinimalApis.Mvc/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /Samples/BlazorMinimalApis.Mvc/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | }, 8 | "AllowedHosts": "*" 9 | } 10 | -------------------------------------------------------------------------------- /Samples/BlazorMinimalApis.Mvc/wwwroot/app.css: -------------------------------------------------------------------------------- 1 | html, body { 2 | font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; 3 | } 4 | 5 | a, .btn-link { 6 | color: #006bb7; 7 | } 8 | 9 | .btn-primary { 10 | color: #fff; 11 | background-color: #1b6ec2; 12 | border-color: #1861ac; 13 | } 14 | 15 | .btn:focus, .btn:active:focus, .btn-link.nav-link:focus, .form-control:focus, .form-check-input:focus { 16 | box-shadow: 0 0 0 0.1rem white, 0 0 0 0.25rem #258cfb; 17 | } 18 | 19 | .content { 20 | padding-top: 1.1rem; 21 | } 22 | 23 | h1:focus { 24 | outline: none; 25 | } 26 | 27 | .valid.modified:not([type=checkbox]) { 28 | outline: 1px solid #26b050; 29 | } 30 | 31 | .invalid { 32 | outline: 1px solid #e50570; 33 | } 34 | 35 | .validation-message { 36 | color: #e50570; 37 | } 38 | 39 | .blazor-error-boundary { 40 | background: url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNTYiIGhlaWdodD0iNDkiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIG92ZXJmbG93PSJoaWRkZW4iPjxkZWZzPjxjbGlwUGF0aCBpZD0iY2xpcDAiPjxyZWN0IHg9IjIzNSIgeT0iNTEiIHdpZHRoPSI1NiIgaGVpZ2h0PSI0OSIvPjwvY2xpcFBhdGg+PC9kZWZzPjxnIGNsaXAtcGF0aD0idXJsKCNjbGlwMCkiIHRyYW5zZm9ybT0idHJhbnNsYXRlKC0yMzUgLTUxKSI+PHBhdGggZD0iTTI2My41MDYgNTFDMjY0LjcxNyA1MSAyNjUuODEzIDUxLjQ4MzcgMjY2LjYwNiA1Mi4yNjU4TDI2Ny4wNTIgNTIuNzk4NyAyNjcuNTM5IDUzLjYyODMgMjkwLjE4NSA5Mi4xODMxIDI5MC41NDUgOTIuNzk1IDI5MC42NTYgOTIuOTk2QzI5MC44NzcgOTMuNTEzIDI5MSA5NC4wODE1IDI5MSA5NC42NzgyIDI5MSA5Ny4wNjUxIDI4OS4wMzggOTkgMjg2LjYxNyA5OUwyNDAuMzgzIDk5QzIzNy45NjMgOTkgMjM2IDk3LjA2NTEgMjM2IDk0LjY3ODIgMjM2IDk0LjM3OTkgMjM2LjAzMSA5NC4wODg2IDIzNi4wODkgOTMuODA3MkwyMzYuMzM4IDkzLjAxNjIgMjM2Ljg1OCA5Mi4xMzE0IDI1OS40NzMgNTMuNjI5NCAyNTkuOTYxIDUyLjc5ODUgMjYwLjQwNyA1Mi4yNjU4QzI2MS4yIDUxLjQ4MzcgMjYyLjI5NiA1MSAyNjMuNTA2IDUxWk0yNjMuNTg2IDY2LjAxODNDMjYwLjczNyA2Ni4wMTgzIDI1OS4zMTMgNjcuMTI0NSAyNTkuMzEzIDY5LjMzNyAyNTkuMzEzIDY5LjYxMDIgMjU5LjMzMiA2OS44NjA4IDI1OS4zNzEgNzAuMDg4N0wyNjEuNzk1IDg0LjAxNjEgMjY1LjM4IDg0LjAxNjEgMjY3LjgyMSA2OS43NDc1QzI2Ny44NiA2OS43MzA5IDI2Ny44NzkgNjkuNTg3NyAyNjcuODc5IDY5LjMxNzkgMjY3Ljg3OSA2Ny4xMTgyIDI2Ni40NDggNjYuMDE4MyAyNjMuNTg2IDY2LjAxODNaTTI2My41NzYgODYuMDU0N0MyNjEuMDQ5IDg2LjA1NDcgMjU5Ljc4NiA4Ny4zMDA1IDI1OS43ODYgODkuNzkyMSAyNTkuNzg2IDkyLjI4MzcgMjYxLjA0OSA5My41Mjk1IDI2My41NzYgOTMuNTI5NSAyNjYuMTE2IDkzLjUyOTUgMjY3LjM4NyA5Mi4yODM3IDI2Ny4zODcgODkuNzkyMSAyNjcuMzg3IDg3LjMwMDUgMjY2LjExNiA4Ni4wNTQ3IDI2My41NzYgODYuMDU0N1oiIGZpbGw9IiNGRkU1MDAiIGZpbGwtcnVsZT0iZXZlbm9kZCIvPjwvZz48L3N2Zz4=) no-repeat 1rem/1.8rem, #b32121; 41 | padding: 1rem 1rem 1rem 3.7rem; 42 | color: white; 43 | } 44 | 45 | .blazor-error-boundary::after { 46 | content: "An error has occurred." 47 | } 48 | -------------------------------------------------------------------------------- /Samples/BlazorMinimalApis.Mvc/wwwroot/favicon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/westonwalker/BlazorMinimalAPI/c45313426c7398f5440a9b2e022d2a99549381bd/Samples/BlazorMinimalApis.Mvc/wwwroot/favicon.png -------------------------------------------------------------------------------- /global.json: -------------------------------------------------------------------------------- 1 | { 2 | "sdk": { 3 | "version": "8.0.100" 4 | } 5 | } --------------------------------------------------------------------------------