Skip to content

Fix ASP0016 false positive for nested anonymous functions - #64174

Merged
halter73 merged 3 commits into
mainfrom
copilot/add-test-nested-anonymous-methods
Aug 11, 2026
Merged

halter73 merged 3 commits into
mainfrom
copilot/add-test-nested-anonymous-methods

Conversation

Copilot AI commented Oct 27, 2025 •

Copy link
Copy Markdown
Contributor

The ASP0016 analyzer incorrectly flagged Task<T> returns from nested anonymous functions as returns from the parent RequestDelegate. This caused false positives when lambdas returning Task<T> were passed to methods like Assert.ThrowsAsync:

app.Run(async context =>
{
    // This lambda returns Task<Stream>, but it's passed to ThrowsAsync, not returned from the RequestDelegate
    var ex = await Assert.ThrowsAsync<InvalidOperationException>(() => upgradeFeature.UpgradeAsync());
});

Changes

  • Added IsReturnFromNestedAnonymousFunction helper that walks the parent chain to detect returns from nested anonymous functions
  • Modified the analyzer to skip return operations that belong to nested anonymous functions rather than the RequestDelegate itself
  • Added test cases covering both simple nested lambdas and lambdas passed to method calls

The fix uses ReferenceEquals to distinguish between the target RequestDelegate and any nested anonymous functions in its body, ensuring only direct returns from the RequestDelegate are analyzed.

Original prompt

This section details on the original issue you should resolve

<issue_title>ASP0016 False positive for nested anonymous methods</issue_title>
<issue_description>You can add the following test to RequestDelegateReturnTypeAnalyzerTests.cs:

    [Fact]
    public async Task AnonymousDelegate_RequestDelegate_ReturnType_InNestedAynonymousDelegate_DoesNotReportDiagnostics()
    {
        await VerifyCS.VerifyAnalyzerAsync(@"
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
var webApp = WebApplication.Create();
webApp.Run((context) =>
{
    Func<Task<DateTime>> _ = () => Task.FromResult(DateTime.Now);
    return Task.CompletedTask;
});
");
    }

And you'll get the following failure:

  Message: 
System.InvalidOperationException : Mismatch between number of diagnostics returned, expected "0" actual "1"

Diagnostics:
// /0/Test0.cs(6,12): warning ASP0016: The method used to create a RequestDelegate returns Task<System.DateTime>. RequestDelegate discards this value. If this isn't intended then change the return type to non-generic Task or, if the delegate is a route handler, cast it to Delegate so the return value is written to the response.
VerifyCS.Diagnostic().WithSpan(6, 12, 10, 2).WithArguments("System.DateTime"),



  Stack Trace: 
DefaultVerifier.Equal[T](T expected, T actual, String message)
AnalyzerTest`1.VerifyDiagnosticResults(IEnumerable`1 actualResults, ImmutableArray`1 analyzers, DiagnosticResult[] expectedResults, IVerifier verifier)
AnalyzerTest`1.VerifyDiagnosticsAsync(EvaluatedProjectState primaryProject, ImmutableArray`1 additionalProjects, DiagnosticResult[] expected, IVerifier verifier, CancellationToken cancellationToken)
AnalyzerTest`1.RunImplAsync(CancellationToken cancellationToken)
AnalyzerTest`1.RunAsync(CancellationToken cancellationToken)
CSharpAnalyzerVerifier`1.VerifyAnalyzerAsync(String source, DiagnosticResult[] expected) line 46
RequestDelegateReturnTypeAnalyzerTests.AnonymousDelegate_RequestDelegate_ReturnType_InNestedAynonymousDelegate_DoesNotReportDiagnostics() line 73
--- End of stack trace from previous location ---

This is incorrect because the Task<System.DateTime> is not being returned directly from the anonymous RequestDelegate, but instead an inner anonymous method which is not a RequestDelegate. This was uncovered by #64120 which resulted in the following line getting incorrectly flagged by ASP0016 even though the lambda calling UpgradeAsync() and returning a Task<Stream> was being passed to ThrowsAsync as a Func<Task<Stream>> and was never converted to a RequestDelegate.

var ex = await Assert.ThrowsAsync<InvalidOperationException>(() => upgradeFeature.UpgradeAsync());

D:\a\_work\1\s\src\Servers\IIS\IIS\test\testassets\InProcessWebSite\Startup.WebSockets.cs(98,17): error ASP0016: The method used to create a RequestDelegate returns Task<System.IO.Stream>. RequestDelegate discards this value. If this isn't intended then change the return type to non-generic Task or, if the delegate is a route handler, cast it to Delegate so the return value is written to the response. (https://aka.ms/aspnet/analyzers) [D:\a\_work\1\s\src\Servers\IIS\IIS\test\testassets\InProcessNewShimWebSite\InProcessNewShimWebSite.csproj::TargetFramework=net8.0]
##[error]src\Servers\IIS\IIS\test\testassets\InProcessWebSite\Startup.WebSockets.cs(98,17): error ASP0016: (NETCORE_ENGINEERING_TELEMETRY=Build) The method used to create a RequestDelegate returns Task<System.IO.Stream>. RequestDelegate discards this value. If this isn't intended then change the return type to non-generic Task or, if the delegate is a route handler, cast it to Delegate so the return value is written to the response. (https://aka.ms/aspnet/analyzers)

https://dev.azure.com/dnceng-public/public/_build/results?buildId=1186969&view=logs&jobId=1e4c7542-9334-5468-a143-1d4c0c4c3006%3Fpr%3D64120&j=4192b01c-4527-54c8-cf65-dc27f588da45&t=ee2d7ee8-2075-51eb-eb72-626500250fa2&s=d654deb9-056d-50a2-1717-90c08683d50a

@JamesNK </issue_description>

<agent_instructions>Fix RequestDelegateReturnTypeAnalyzer so when it recurses over the operations in anonymousFunction.Body it avoids considering the IReturnOperation that belong to nested IAnonymousFunctionOperation.</agent_instructions>

Comments on the Issue (you are @copilot in this section)


💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more Copilot coding agent tips in the docs.

@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Greetings human! You've submitted a PR that modifies code that is shared with https://github.com/dotnet/runtime . Please make sure you synchronize this code with the changes in that repo!

Copilot AI changed the title [WIP] Add test for nested anonymous methods in RequestDelegateReturnTypeAnalyzerTests Fix ASP0016 false positive for nested anonymous functions Oct 27, 2025
Copilot AI requested a review from halter73 October 27, 2025 23:39
@github-actions github-actions Bot added the needs-area-label Used by the dotnet-issue-labeler to label those issues which couldn't be triaged automatically label Feb 10, 2026
@halter73
halter73 marked this pull request as ready for review August 7, 2026 00:22
@halter73
halter73 requested review from Youssef1313 and Copilot August 7, 2026 00:22

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR fixes an ASP0016 analyzer false positive by ensuring Task<T> returns inside nested anonymous functions within a RequestDelegate body are not treated as returns from the RequestDelegate itself.

Changes:

  • Added IsReturnFromNestedAnonymousFunction to detect whether an IReturnOperation belongs to a nested anonymous function (via parent-chain walk).
  • Updated RequestDelegateReturnTypeAnalyzer to skip such nested-function returns when evaluating Task<T> return diagnostics.
  • Added regression tests covering nested lambdas both as assigned delegates and as lambdas passed to a method parameter.
Show a summary per file
File Description
src/Framework/AspNetCoreAnalyzers/src/Analyzers/Http/RequestDelegateReturnTypeAnalyzer.cs Skips IReturnOperations that are part of nested anonymous functions so ASP0016 only analyzes direct RequestDelegate returns.
src/Framework/AspNetCoreAnalyzers/test/Http/RequestDelegateReturnTypeAnalyzerTests.cs Adds regression tests ensuring nested-lambda Task<T> returns don’t trigger ASP0016.

Copilot's findings

  • Files reviewed: 2/2 changed files
  • Comments generated: 1

Body.Descendants() walks into local function bodies too, but a return
inside a local function has a parent chain of

    Block -> ILocalFunctionOperation -> Block -> IAnonymousFunctionOperation

so it never passes through an IAnonymousFunctionOperation. The parent walk
reached the target lambda, and the local function's return was still
treated as the RequestDelegate's own.

Treat ILocalFunctionOperation as a nesting boundary as well, and rename the
helper to IsReturnFromNestedFunction to match. Without this the analyzer
both warns on valid code and, because it bails after the first match, can
report the nested function's return type instead of the RequestDelegate's.

Also flip the unreachable fallback to false so a broken assumption surfaces
as a reported false positive rather than a silently missing diagnostic.

Co-authored-by: Copilot App <[email protected]>

@Youssef1313 Youssef1313 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@halter73
halter73 merged commit 3600ca0 into main Aug 11, 2026
27 checks passed
@halter73
halter73 deleted the copilot/add-test-nested-anonymous-methods branch August 11, 2026 15:22
@dotnet-milestone-bot dotnet-milestone-bot Bot added this to the 11.0-rc1 milestone Aug 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Attention: Shared Code Modified needs-area-label Used by the dotnet-issue-labeler to label those issues which couldn't be triaged automatically

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ASP0016 False positive for nested anonymous methods

4 participants