Skip to content

Commit f307233

Browse files
authored
Handle null attributes in generated delegates (#7210)
1 parent b5d8fe9 commit f307233

File tree

2 files changed

+28
-2
lines changed

2 files changed

+28
-2
lines changed

src/Http/Routing/src/Builder/EndpointRouteBuilderExtensions.cs

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -327,9 +327,15 @@ public static IEndpointConventionBuilder Map(
327327
};
328328

329329
// Add delegate attributes as metadata
330-
foreach (var attribute in requestDelegate.Method.GetCustomAttributes())
330+
var attributes = requestDelegate.Method.GetCustomAttributes();
331+
332+
// This can be null if the delegate is a dynamic method or compiled from an expression tree
333+
if (attributes != null)
331334
{
332-
routeEndpointBuilder.Metadata.Add(attribute);
335+
foreach (var attribute in attributes)
336+
{
337+
routeEndpointBuilder.Metadata.Add(attribute);
338+
}
333339
}
334340

335341
if (metadata != null)

src/Http/Routing/test/UnitTests/Builder/MapEndpointEndpointDataSourceBuilderExtensionsTest.cs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
33

44
using System;
5+
using System.Linq.Expressions;
56
using System.Threading.Tasks;
67
using Microsoft.AspNetCore.Http;
78
using Microsoft.AspNetCore.Routing;
@@ -133,6 +134,25 @@ public void MapEndpoint_ExplicitMetadataAddedAfterAttributeMetadata()
133134
Assert.IsType<Metadata>(endpointBuilder1.Metadata[2]);
134135
}
135136

137+
[Fact]
138+
public void MapEndpoint_GeneratedDelegateWorks()
139+
{
140+
// Arrange
141+
var builder = new DefaultEndpointRouteBuilder();
142+
143+
Expression<RequestDelegate> handler = context => Task.CompletedTask;
144+
145+
// Act
146+
var endpointBuilder = builder.Map(RoutePatternFactory.Parse("/"), "Display name!", handler.Compile(), new Metadata());
147+
148+
// Assert
149+
var endpointBuilder1 = GetRouteEndpointBuilder(builder);
150+
Assert.Equal("Display name!", endpointBuilder1.DisplayName);
151+
Assert.Equal("/", endpointBuilder1.RoutePattern.RawText);
152+
Assert.Equal(1, endpointBuilder1.Metadata.Count);
153+
Assert.IsType<Metadata>(endpointBuilder1.Metadata[0]);
154+
}
155+
136156
[Attribute1]
137157
[Attribute2]
138158
private static Task Handle(HttpContext context) => Task.CompletedTask;

0 commit comments

Comments
 (0)