Skip to content

Commit 0cfd468

Browse files
authored
Fix request delegate analyzer error on null return type (#44534)
1 parent 4faa84c commit 0cfd468

File tree

2 files changed

+40
-1
lines changed

2 files changed

+40
-1
lines changed

src/Framework/AspNetCoreAnalyzers/src/Analyzers/Http/RequestDelegateReturnTypeAnalyzer.cs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,10 @@ public override void Initialize(AnalysisContext context)
5959
var resolvedOperation = WalkDownConversion(returnedValue);
6060
var returnType = resolvedOperation.Type;
6161

62-
if (SymbolEqualityComparer.Default.Equals(returnType.OriginalDefinition, wellKnownTypes.TaskOfT))
62+
// Return type could be null if:
63+
// 1. The method returns null.
64+
// 2. The method throws an exception.
65+
if (returnType != null && SymbolEqualityComparer.Default.Equals(returnType.OriginalDefinition, wellKnownTypes.TaskOfT))
6366
{
6467
AddDiagnosticWarning(context, anonymousFunction.Syntax.GetLocation(), returnType);
6568
return;

src/Framework/AspNetCoreAnalyzers/test/Http/RequestDelegateReturnTypeAnalyzerTests.cs

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,42 @@ namespace Microsoft.AspNetCore.Analyzers.Http;
1010

1111
public class RequestDelegateReturnTypeAnalyzerTests
1212
{
13+
[Fact]
14+
public async Task AnonymousDelegate_RequestDelegate_ThrowError_NoDiagnostics()
15+
{
16+
// Arrange & Act & Assert
17+
await VerifyCS.VerifyAnalyzerAsync(@"
18+
using System;
19+
using System.Threading.Tasks;
20+
using Microsoft.AspNetCore.Http;
21+
using Microsoft.AspNetCore.Builder;
22+
var webApp = WebApplication.Create();
23+
webApp.Use(async (HttpContext context, Func<Task> next) =>
24+
{
25+
context.SetEndpoint(new Endpoint(c => throw new Exception(), EndpointMetadataCollection.Empty, ""Test""));
26+
await next();
27+
});
28+
");
29+
}
30+
31+
[Fact]
32+
public async Task AnonymousDelegate_RequestDelegate_ReturnNull_NoDiagnostics()
33+
{
34+
// Arrange & Act & Assert
35+
await VerifyCS.VerifyAnalyzerAsync(@"
36+
using System;
37+
using System.Threading.Tasks;
38+
using Microsoft.AspNetCore.Http;
39+
using Microsoft.AspNetCore.Builder;
40+
var webApp = WebApplication.Create();
41+
webApp.Use(async (HttpContext context, Func<Task> next) =>
42+
{
43+
context.SetEndpoint(new Endpoint(c => null, EndpointMetadataCollection.Empty, ""Test""));
44+
await next();
45+
});
46+
");
47+
}
48+
1349
[Fact]
1450
public async Task AnonymousDelegate_RequestDelegate_ReturnType_EndpointCtor_ReportDiagnostics()
1551
{

0 commit comments

Comments
 (0)