forked from agentic-review-benchmarks/aspnetcore
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRazorComponentEndpointsStartup.cs
More file actions
301 lines (257 loc) · 12.7 KB
/
RazorComponentEndpointsStartup.cs
File metadata and controls
301 lines (257 loc) · 12.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Globalization;
using System.Reflection;
using System.Security.Claims;
using System.Web;
using Components.TestServer.RazorComponents;
using Components.TestServer.RazorComponents.Pages.Forms;
using Components.TestServer.RazorComponents.Pages.PersistentState;
using Components.TestServer.Services;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Server.Circuits;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Server;
using Microsoft.AspNetCore.Mvc;
using TestContentPackage;
using TestContentPackage.Services;
namespace TestServer;
public class RazorComponentEndpointsStartup<TRootComponent>
{
public RazorComponentEndpointsStartup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddValidation();
services.AddRazorComponents(options =>
{
options.MaxFormMappingErrorCount = 10;
options.MaxFormMappingRecursionDepth = 5;
options.MaxFormMappingCollectionSize = 100;
})
.RegisterPersistentService<InteractiveServerService>(RenderMode.InteractiveServer)
.RegisterPersistentService<InteractiveAutoService>(RenderMode.InteractiveAuto)
.RegisterPersistentService<InteractiveWebAssemblyService>(RenderMode.InteractiveWebAssembly)
.AddInteractiveWebAssemblyComponents()
.AddInteractiveServerComponents(options =>
{
if (Configuration.GetValue<bool>("DisableReconnectionCache"))
{
// This disables the reconnection cache, which forces the server to persist the circuit state.
options.DisconnectedCircuitMaxRetained = 0;
options.DetailedErrors = true;
}
options.RootComponents.RegisterForJavaScript<TestContentPackage.PersistentComponents.ComponentWithPersistentState>("dynamic-js-root-counter");
})
.AddAuthenticationStateSerialization(options =>
{
bool.TryParse(Configuration["SerializeAllClaims"], out var serializeAllClaims);
options.SerializeAllClaims = serializeAllClaims;
});
if (Configuration.GetValue<bool>("UseHybridCache"))
{
services.AddHybridCache();
}
services.AddScoped<InteractiveWebAssemblyService>();
services.AddScoped<InteractiveServerService>();
services.AddScoped<InteractiveAutoService>();
// Register custom serializer for E2E testing of persistent component state serialization extensibility
services.AddSingleton<PersistentComponentStateSerializer<int>, CustomIntSerializer>();
services.AddHttpContextAccessor();
services.AddSingleton<AsyncOperationService>();
services.AddCascadingAuthenticationState();
services.AddSingleton<WebSocketCompressionConfiguration>();
var circuitContextAccessor = new TestCircuitContextAccessor();
services.AddSingleton<CircuitHandler>(circuitContextAccessor);
services.AddSingleton(circuitContextAccessor);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
var enUs = new CultureInfo("en-US");
CultureInfo.DefaultThreadCurrentCulture = enUs;
CultureInfo.DefaultThreadCurrentUICulture = enUs;
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.Map("/subdir", app =>
{
app.Map("/reexecution", reexecutionApp =>
{
app.Map("/trigger-404", app =>
{
app.Run(async context =>
{
context.Response.StatusCode = 404;
await context.Response.WriteAsync("Triggered a 404 status code.");
});
});
reexecutionApp.UseStatusCodePagesWithReExecute("/not-found-reexecute", createScopeForStatusCodePages: true);
reexecutionApp.UseRouting();
reexecutionApp.UseAntiforgery();
ConfigureEndpoints(reexecutionApp, env);
});
app.Map("/interactive-reexecution", reexecutionApp =>
{
reexecutionApp.UseStatusCodePagesWithReExecute("/not-found-reexecute-interactive", createScopeForStatusCodePages: true);
reexecutionApp.UseRouting();
reexecutionApp.UseAntiforgery();
ConfigureEndpoints(reexecutionApp, env);
});
ConfigureSubdirPipeline(app, env);
});
}
private void ConfigureSubdirPipeline(IApplicationBuilder app, IWebHostEnvironment env)
{
WebAssemblyTestHelper.ServeCoopHeadersIfWebAssemblyThreadingEnabled(app);
if (!env.IsDevelopment())
{
app.UseExceptionHandler("/Error", createScopeForErrors: true);
}
app.UseRouting();
UseFakeAuthState(app);
app.UseAntiforgery();
app.Use((ctx, nxt) =>
{
if (ctx.Request.Query.ContainsKey("add-csp"))
{
ctx.Response.Headers.Add("Content-Security-Policy", "script-src 'self' 'unsafe-inline'");
}
return nxt();
});
ConfigureEndpoints(app, env);
}
private void ConfigureEndpoints(IApplicationBuilder app, IWebHostEnvironment env)
{
_ = app.UseEndpoints(endpoints =>
{
var contentRootStaticAssetsPath = Path.Combine(env.ContentRootPath, "Components.TestServer.staticwebassets.endpoints.json");
if (File.Exists(contentRootStaticAssetsPath))
{
endpoints.MapStaticAssets(contentRootStaticAssetsPath);
}
else
{
endpoints.MapStaticAssets();
}
_ = endpoints.MapRazorComponents<TRootComponent>()
.AddAdditionalAssemblies(Assembly.Load("TestContentPackage"))
.AddAdditionalAssemblies(Assembly.Load("Components.WasmMinimal"))
.AddInteractiveServerRenderMode(options =>
{
var config = app.ApplicationServices.GetRequiredService<WebSocketCompressionConfiguration>();
options.DisableWebSocketCompression = config.IsCompressionDisabled;
options.ContentSecurityFrameAncestorsPolicy = config.CspPolicy;
options.ConfigureWebSocketAcceptContext = config.ConfigureWebSocketAcceptContext;
})
.AddInteractiveWebAssemblyRenderMode(options => options.PathPrefix = "/WasmMinimal");
NotEnabledStreamingRenderingComponent.MapEndpoints(endpoints);
StreamingRenderingForm.MapEndpoints(endpoints);
InteractiveStreamingRenderingComponent.MapEndpoints(endpoints);
MapEnhancedNavigationEndpoints(endpoints);
});
}
internal static void UseFakeAuthState(IApplicationBuilder app)
{
app.Use((HttpContext context, Func<Task> next) =>
{
// Completely insecure fake auth system with no password for tests. Do not do anything like this in real apps.
// It accepts a query parameter 'username' and then sets or deletes a cookie to hold that, and supplies a principal
// using this username (taken either from the cookie or query param).
string GetQueryOrDefault(string queryKey, string defaultValue) =>
context.Request.Query.TryGetValue(queryKey, out var value) ? value : defaultValue;
const string cookieKey = "fake_username";
var username = GetQueryOrDefault("username", context.Request.Cookies[cookieKey]);
if (context.Request.Query.ContainsKey("username"))
{
if (string.IsNullOrEmpty(username))
{
context.Response.Cookies.Delete(cookieKey);
}
else
{
// Expires when browser is closed, so tests won't interfere with each other
context.Response.Cookies.Append(cookieKey, username);
}
}
var nameClaimType = GetQueryOrDefault("nameClaimType", ClaimTypes.Name);
var roleClaimType = GetQueryOrDefault("roleClaimType", ClaimTypes.Role);
if (!string.IsNullOrEmpty(username))
{
var claims = new List<Claim>
{
new Claim(nameClaimType, username),
new Claim(roleClaimType, "test-role-1"),
new Claim(roleClaimType, "test-role-2"),
new Claim("test-claim", "Test claim value"),
};
context.User = new ClaimsPrincipal(new ClaimsIdentity(claims, "FakeAuthenticationType", nameClaimType, roleClaimType));
}
return next();
});
}
private static void MapEnhancedNavigationEndpoints(IEndpointRouteBuilder endpoints)
{
// Used when testing that enhanced nav can show non-HTML responses (which it does by doing a full navigation)
endpoints.Map("/nav/non-html-response", () => "Hello, this is plain text");
// Used when testing that enhanced nav displays content even if the response is an error status code
endpoints.Map("/nav/give-404-with-content", async (HttpResponse response) =>
{
response.StatusCode = 404;
response.ContentType = "text/html";
await response.WriteAsync("<h1>404</h1><p>Sorry, there's nothing here! This is a custom server-generated 404 message.</p>");
});
// Used when testing that enhanced nav includes "Accept: text/html"
endpoints.Map("/nav/list-headers", async (HttpRequest request, HttpResponse response) =>
{
// We have to accept enanced nav explicitly since the test is checking what headers are sent for enhanced nav requests
// Otherwise, the client will retry as a non-enhanced-nav request and the UI won't show the enhanced nav headers
response.Headers.Add("blazor-enhanced-nav", "allow");
response.ContentType = "text/html";
await response.WriteAsync("<ul id='all-headers'>");
foreach (var header in request.Headers)
{
await response.WriteAsync($"<li>{HttpUtility.HtmlEncode(header.Key)}: {HttpUtility.HtmlEncode(header.Value)}</li>");
}
await response.WriteAsync("</ul>");
});
// Used in the redirection to non-Blazor endpoints tests
endpoints.MapGet("redirect/nonblazor/get", PerformRedirection);
endpoints.MapPost("redirect/nonblazor/post", PerformRedirection);
// Used when testing enhanced navigation to non-Blazor endpoints
endpoints.Map("/nav/non-blazor-html-response", async (HttpResponse response) =>
{
response.ContentType = "text/html";
await response.WriteAsync("<html><body><h1>This is a non-Blazor endpoint</h1><p>That's all</p></body></html>");
});
endpoints.MapPost("api/antiforgery-form", (
[FromForm] string value,
[FromForm(Name = "__RequestVerificationToken")] string? inFormCsrfToken,
[FromHeader(Name = "RequestVerificationToken")] string? inHeaderCsrfToken) =>
{
// We shouldn't get this far without a valid CSRF token, but we'll double check it's there.
if (string.IsNullOrEmpty(inFormCsrfToken) && string.IsNullOrEmpty(inHeaderCsrfToken))
{
throw new InvalidOperationException("Invalid POST to api/antiforgery-form!");
}
return TypedResults.Text($"<p id='pass'>Hello {value}!</p>", "text/html");
});
endpoints.Map("/forms/endpoint-that-never-finishes-rendering", (HttpResponse response, CancellationToken token) =>
{
return Task.Delay(Timeout.Infinite, token);
});
endpoints.Map("/test-formaction", () => "Formaction url");
static Task PerformRedirection(HttpRequest request, HttpResponse response)
{
response.Redirect(request.Query["external"] == "true"
? "https://microsoft.com"
: $"{request.PathBase}/nav/scroll-to-hash#some-content");
return Task.CompletedTask;
}
}
}