我正在构建一个 ASP.NET Core 9 Minimal API,其中我正在处理的端点正在接收表单数据,但无法绑定其中一个属性的值。该属性是一个强类型 id 结构体(使用 Andrew Lock 的 StronglyTypedId 包)。该包确实生成了 aTypeConverter
和 a JsonConverter
,但似乎都没有用于模型绑定。
过去几个小时我一直在寻找解决方案但一无所获,所以我来这里询问是否应该为最小 API 做一些具体的事情来将模型绑定到结构?
下面是我能写出的最短的代码来解释我的意思。如果我传递一个值,它会正确绑定,但如果我按照模型的定义将其保留为空,则会引发以下异常:
Microsoft.AspNetCore.Http.BadHttpRequestException:值“”对于“Id”无效。
[StronglyTypedId(Template.Int, TypedIds.Int, TypedIds.IntEfCore)]
public readonly partial struct TestId;
public static class DoSomething {
[ValidateNever]
public sealed class Command :
IRequest<CommandResponse> {
public TestId? Id { get; init; }
}
public sealed class CommandResponse;
}
file sealed class CommandHandler :
IRequestHandler<Command, CommandResponse> {
public Task<CommandResponse> Handle(
Command command,
CancellationToken cancellationToken) => Task.FromResult(new CommandResponse());
}
internal static class Endpoints {
private const string _tag = nameof(Optimize);
public static WebApplication MapOptimize(
this WebApplication app) {
app.MapPost("/v1/do-something", DoSomethingAsync)
.Accepts<DoSomethingCommand>("multipart/form-data")
.DisableAntiforgery()
.Produces<DoSomethingCommandResponse>()
.WithTags(_tag);
return app;
}
private static async Task<IResult> DoSomethingAsync(
[FromForm] DoSomethingCommand command,
[FromServices] IMediator mediator,
CancellationToken cancellationToken) {
var response = await mediator.Send(command, cancellationToken).ConfigureAwait(false);
return Results.Ok(response);
}
}
这是表单绑定的 Minimal API 中的一个已知问题,并且不限于
StronglyTypedId
。问题在于,在这种情况下,可空值类型无法正确处理(不仅是StronglyTypedId
's,iepublic class DoSomethingCommand { public int? TestId { get; set; } }
也会出现同样的问题)。作为解决方法,您可以使用原始值并手动解析它:
根据这个 github 问题中的回复,据我了解,这个问题应该在第 10 版中得到修复。
另请参阅最小 API 端点不允许为可空 int 为空?
正如在这个 GitHub 问题中所看到的,Minimal API 的模型绑定扩展功能仅限于静态方法
TryParse
和BindAsync
。给你的结构其中之一,模型绑定应该开始工作。