Skip to content

Commit cbfc558

Browse files
Fix disabling anti-forgery check on route groups (#51244)
1 parent 844e28b commit cbfc558

File tree

2 files changed

+48
-1
lines changed

2 files changed

+48
-1
lines changed

src/Http/Routing/src/Builder/RoutingEndpointConventionBuilderExtensions.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -159,7 +159,7 @@ public static TBuilder DisableAntiforgery<TBuilder>(this TBuilder builder) where
159159
{
160160
ArgumentNullException.ThrowIfNull(builder);
161161

162-
builder.WithMetadata(AntiforgeryMetadata.ValidationNotRequired);
162+
builder.Finally(builder => builder.Metadata.Add(AntiforgeryMetadata.ValidationNotRequired));
163163
return builder;
164164
}
165165

src/Http/Routing/test/FunctionalTests/MinimalFormTests.cs

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -292,6 +292,53 @@ public async Task MapPost_WithForm_WithoutAntiforgery_WithoutMiddleware_Works()
292292
Assert.Equal(DateTime.Today.AddDays(1), result.DueDate);
293293
}
294294

295+
[Fact]
296+
public async Task MapPost_WithForm_WithoutAntiforgery_AndRouteGroup_WithoutMiddleware_Works()
297+
{
298+
using var host = new HostBuilder()
299+
.ConfigureWebHost(webHostBuilder =>
300+
{
301+
webHostBuilder
302+
.Configure(app =>
303+
{
304+
app.UseRouting();
305+
app.UseEndpoints(b =>
306+
{
307+
var group = b.MapGroup("/todo").DisableAntiforgery();
308+
group.MapPost("", ([FromForm] Todo todo) => todo);
309+
});
310+
})
311+
.UseTestServer();
312+
})
313+
.ConfigureServices(services =>
314+
{
315+
services.AddRouting();
316+
services.AddAntiforgery();
317+
})
318+
.Build();
319+
320+
using var server = host.GetTestServer();
321+
await host.StartAsync();
322+
var client = server.CreateClient();
323+
324+
var request = new HttpRequestMessage(HttpMethod.Post, "todo");
325+
var nameValueCollection = new List<KeyValuePair<string, string>>
326+
{
327+
new KeyValuePair<string,string>("name", "Test task"),
328+
new KeyValuePair<string,string>("isComplete", "false"),
329+
new KeyValuePair<string,string>("dueDate", DateTime.Today.AddDays(1).ToString(CultureInfo.InvariantCulture)),
330+
};
331+
request.Content = new FormUrlEncodedContent(nameValueCollection);
332+
333+
var response = await client.SendAsync(request);
334+
response.EnsureSuccessStatusCode();
335+
var body = await response.Content.ReadAsStringAsync();
336+
var result = JsonSerializer.Deserialize<Todo>(body, SerializerOptions);
337+
Assert.Equal("Test task", result.Name);
338+
Assert.False(result.IsCompleted);
339+
Assert.Equal(DateTime.Today.AddDays(1), result.DueDate);
340+
}
341+
295342
public static IEnumerable<object[]> RequestDelegateData
296343
{
297344
get

0 commit comments

Comments
 (0)