dotnet / Scaffolding

Code generators to speed up development.
MIT License
624 stars 223 forks source link

Update the Blazor Identity scaffolder to exclude scaffolded pages from interactive routing when targeting .NET 9 #2717

Open danroth27 opened 3 months ago

danroth27 commented 3 months ago

In .NET 9 Preview 4, we added a feature to exclude pages from interactive routing using the new [ExcludeFromInteractiveRouting] attribute. This feature simplifies using static pages in a Blazor app that is otherwise setup with global interactivity using an interactive router. This feature should be used with the Blazor Identity scaffolder.

To use the feature, we need to include an _Imports.razor file in the folder with the scaffolded components that includes the @attribute [ExcludeFormInteractiveRouting] directive. This will add metadata to the page's endpoint that can then be used to configure the router appropriately when the app is setup for global interactivity. If the app is using global interactivity, the required changes in App.razor look like this (substituting for InteractiveServer the actual render mode used globally by the app):

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <base href="/" />
    <link rel="stylesheet" href="bootstrap/bootstrap.min.css" />
    <link rel="stylesheet" href="app.css" />
    <link rel="stylesheet" href="BlazorApp25.styles.css" />
    <link rel="icon" type="image/png" href="favicon.png" />
-    <HeadOutlet @rendermode="InteractiveServer" />
+    <HeadOutlet @rendermode="PageRenderMode" />
</head>

<body>
-    <Routes @rendermode="InteractiveServer" />
+    <Routes @rendermode="PageRenderMode" />
    <script src="_framework/blazor.web.js"></script>
</body>

</html

+ @code {
+    [CascadingParameter]
+    private HttpContext HttpContext { get; set; } = default!;
+
+    private IComponentRenderMode? PageRenderMode =>
+        HttpContext.AcceptsInteractiveRouting() ? InteractiveServer : null; 
+}

We've already updated the Blazor Web App template in .NET 9 to use the [ExcludeFromInteractiveRouting] feature when the template uses global interactivity and ASP.NET Core Identity for auth. You can see the related changes that should be emulated in the Blazor Identity scaffolder in this PR: https://github.com/dotnet/aspnetcore/pull/55157/files#diff-fd16fee9145b20d81c4c2a48e4daf91fef913bd729d395185595bae2fc1daae2.