1

I have the following minimal API code:

routeBuilder.MapGet("/test", TestMethod);
routeBuilder.MapPost("/test2", TestMethod2);

...

public static async Task<IResult> TestMethod(HttpContext http)
{
    ...
}

public static async Task<IResult> TestMethod2(HttpContext http, DataContext context, [FromForm] string value)
{
    ...
}

When compiling I get the warning "ASP0016 Do not return a value from RequestDelegate" of the MapGet with TestMethod. TestMethod2 does not get this warning. Why is this happening? The documentation for that warning does not explain the issue in this case at all.

2 Answers 2

4

This is a "known issue" coming from the fact that async (Task-returning) handler functions accepting only HttpContext match the RequestDelegate signature:

public delegate Task RequestDelegate(HttpContext context);

And the corresponding overloads are selected, so the value in the Task<T> returned by TestMethod will be ignored making Minimal APIs methods like 'MapGet'/'MapPost' etc. not working correctly.

Team is not planning to fix it ATM (or it is not easily fixable with current ASP.NET Core infrastructure) this rule was created (ASP0016: Do not return a value from RequestDelegate):

Do not return a value Delegates provided to APIs that expect RequestDelegate. For example, the following sample returns a Task<string> where the string value of the Task will be discarded.

There are multiple workarounds:

  • Adding extra parameter so the RequestDelegate is not matched (CancellationToken is usually a good candidate):

    public static async Task<IResult> TestMethod(HttpContext http, 
         CancellationToken ct)
    
  • Switching to another special type binding like HttpRequest:

    public static async Task<IResult> TestMethod(HttpRequest request) // add HttpResponse response if needed
    
  • Casting to correct delegate type:

    routeBuilder.MapGet("/test", (Delegate)TestMethod);
    

More info:

Sign up to request clarification or add additional context in comments.

Comments

2

The extension method MapGet has two versions: one takes Delegate and the other RequestDelegate. For some reason this method is seen as the latter and it's not allowed to return any values. Implicitly casting it to Delegate uses the correct overload, removes the warning, and returns the correct data to the browser:

routeBuilder.MapGet("/test", (Delegate)TestMethod);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.