Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NET 6 Minimal API -'No public static bool Request.TryParse(string, out Request) method found for request

Using .NET 6 I have the following Minimal API in Program.cs:

WebApplicationBuilder builder = WebApplication.CreateBuilder();

builder.Services.AddMvcCore();
builder.Services.AddRouting();

await using WebApplication application = builder.Build();

application.UseRouting();

application.MapGet("/weatherforecast", () => { });

application.MapGet("countries", async ([FromQuery]Request request, IMediator mediator) => {
  Payload<List<Response>> payload = await mediator.Send(request);
  return Results.Ok(payload);
});

await application.RunAsync();

Where Request is:

public class Request { 
  public List<Int32> Ids { get; set; } = new List<Int32>();
} 

When I run the application I get the error on "countries" endpoint:

Exception thrown: 'System.InvalidOperationException' in Microsoft.AspNetCore.Http.Extensions.dll: 'No public static bool Request.TryParse(string, out Request) method found for request.'
   at Microsoft.AspNetCore.Http.RequestDelegateFactory.BindParameterFromValue(ParameterInfo parameter, Expression valueExpression, FactoryContext factoryContext, String source)
   at Microsoft.AspNetCore.Http.RequestDelegateFactory.CreateArgument(ParameterInfo parameter, FactoryContext factoryContext)
   at Microsoft.AspNetCore.Http.RequestDelegateFactory.CreateArguments(ParameterInfo[] parameters, FactoryContext factoryContext)
   at Microsoft.AspNetCore.Http.RequestDelegateFactory.CreateTargetableRequestDelegate(MethodInfo methodInfo, Expression targetExpression, FactoryContext factoryContext)
   at Microsoft.AspNetCore.Http.RequestDelegateFactory.Create(Delegate handler, RequestDelegateFactoryOptions options)
   at Microsoft.AspNetCore.Builder.EndpointRouteBuilderExtensions.Map(IEndpointRouteBuilder endpoints, RoutePattern pattern, Delegate handler, Boolean disableInferBodyFromParameters)
   at Microsoft.AspNetCore.Builder.EndpointRouteBuilderExtensions.MapMethods(IEndpointRouteBuilder endpoints, String pattern, IEnumerable`1 httpMethods, Delegate handler)
   at Microsoft.AspNetCore.Builder.EndpointRouteBuilderExtensions.MapGet(IEndpointRouteBuilder endpoints, String pattern, Delegate handler)

What am I missing?

like image 271
Miguel Moura Avatar asked Jan 23 '26 13:01

Miguel Moura


1 Answers

As of dotnet 7, you can use the [AsParameters] attribute as follows:

application.MapGet("countries", async ([AsParameters] Request request, IMediator mediator) => {
  Payload<List<Response>> payload = await mediator.Send(request);
  return Results.Ok(payload);
});
like image 164
Dave Avatar answered Jan 26 '26 01:01

Dave



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!