Home > Software engineering >  NET 6 Minimal API -'No public static bool Request.TryParse(string, out Request) method found fo
NET 6 Minimal API -'No public static bool Request.TryParse(string, out Request) method found fo

Time:12-08

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?

CodePudding user response:

The error basically means that ASP.NET Core doesn't know how to bind your querystring to the Request you have defined.

Is Request a custom type? If so, you need to add a static TryParse method which takes a string (the query string), and out parameter of the Request object which you will need to initialize by parsing the query string.

You can read more about this in the official documentation

  • Related