NET 6 Minimal API -'No public static bool Request.TryParse(string, out Request) 方法找到请求

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

使用 .NET 6 我在 Program.cs 中有以下最小 API:

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();

其中 Request 是:

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

当我 运行 应用程序时,我在“国家”端点上收到错误消息:

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)

我错过了什么?

该错误基本上意味着 ASP.NET Core 不知道如何将您的查询字符串绑定到您定义的 Request

Request是自定义类型吗?如果是这样,您需要添加一个静态 TryParse 方法,它接受一个字符串(查询字符串),以及您需要通过解析查询字符串来初始化的 Request 对象的输出参数。

您可以在 official documentation

中阅读更多相关信息