Handle null attributes in generated delegates (#7210)

This commit is contained in:
David Fowler 2019-02-02 06:18:54 -08:00 committed by GitHub
parent b5d8fe9630
commit f3072339de
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 28 additions and 2 deletions

View File

@ -327,9 +327,15 @@ namespace Microsoft.AspNetCore.Builder
};
// Add delegate attributes as metadata
foreach (var attribute in requestDelegate.Method.GetCustomAttributes())
var attributes = requestDelegate.Method.GetCustomAttributes();
// This can be null if the delegate is a dynamic method or compiled from an expression tree
if (attributes != null)
{
routeEndpointBuilder.Metadata.Add(attribute);
foreach (var attribute in attributes)
{
routeEndpointBuilder.Metadata.Add(attribute);
}
}
if (metadata != null)

View File

@ -2,6 +2,7 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
@ -133,6 +134,25 @@ namespace Microsoft.AspNetCore.Builder
Assert.IsType<Metadata>(endpointBuilder1.Metadata[2]);
}
[Fact]
public void MapEndpoint_GeneratedDelegateWorks()
{
// Arrange
var builder = new DefaultEndpointRouteBuilder();
Expression<RequestDelegate> handler = context => Task.CompletedTask;
// Act
var endpointBuilder = builder.Map(RoutePatternFactory.Parse("/"), "Display name!", handler.Compile(), new Metadata());
// Assert
var endpointBuilder1 = GetRouteEndpointBuilder(builder);
Assert.Equal("Display name!", endpointBuilder1.DisplayName);
Assert.Equal("/", endpointBuilder1.RoutePattern.RawText);
Assert.Equal(1, endpointBuilder1.Metadata.Count);
Assert.IsType<Metadata>(endpointBuilder1.Metadata[0]);
}
[Attribute1]
[Attribute2]
private static Task Handle(HttpContext context) => Task.CompletedTask;