.NET 5.0 Web API不适用于具有必需属性的记录 [英] .NET 5.0 Web API won't work with record featuring required properties
问题描述
我使用C#9.0 record
类型作为.NET 5.0 Web API项目的绑定模型.一些属性是必需的.
I'm using a C# 9.0 record
type as a binding model for a .NET 5.0 Web API project. Some of the properties are required.
我正在使用 record
位置语法,但收到错误.
I'm using the record
positional syntax, but am receiving errors.
public record Mail(
System.Guid? Id,
[property: Required]
string From,
[property: Required]
string[] Tos,
[property: Required]
string Subject,
string[]? Ccs,
string[]? Bccs,
[property: Required]
Content[] Contents,
Attachment[]? Attachments
);
然后将其作为我的 Index
操作的绑定模型公开:
This is then exposed as the binding model for my Index
action:
public async Task<ActionResult> Index(Service.Models.Mail mailRequest)
{
…
}
但是,每当我尝试发出请求时,都会出现以下错误:
Whenever I try to make a request, however, I receive the following error:
记录类型'Service.Models.Mail'具有在属性'Contents'上定义的验证元数据,该数据将被忽略.内容"是记录主构造函数中的一个参数,并且验证元数据必须与该构造函数参数相关联.
Record type 'Service.Models.Mail' has validation metadata defined on property 'Contents' that will be ignored. 'Contents' is a parameter in the record primary constructor and validation metadata must be associated with the constructor parameter.
我尝试删除了 Contents
属性上的属性,但是下一个(先前的)属性却失败了.我尝试使用 [param:…]
代替 [property:…]
,并混合它们,但始终会出现相同的错误.
I tried removing the attribute on the Contents
property, but it then fails for the next (prior) property. I tried using [param: …]
instead of [property: …]
, as well as mixing them, but keep getting the same kind of error.
我环顾四周,没有发现关于C#9记录以不同方式处理批注的任何建议.我已尽力而为,但除了将记录转换为POCO之外,我一无所有.
I looked around the web, and haven't found any suggestion of handling annotations differently for C# 9 records. I did my best, but I'm out of ideas—outside of converting my records to POCOs.
推荐答案
我放弃了使用Positional构造函数,并且对属性进行了详细的完整声明,因此可以正常工作.
I gave up using Positional constructor, and with the verbose full declaration of the properties, it works.
public record Mail
{
public System.Guid? Id { get; init; }
[Required]
public string From { get; init; }
[Required]
public string[] Tos { get; init; }
[Required]
public string Subject { get; init; }
public string[]? Ccs { get; init; }
public string[]? Bccs { get; init; }
[Required]
public Content[] Contents { get; init; }
public Attachment[]? Attachments { get; init; }
public Status? Status { get; init; }
public Mail(Guid? id, string @from, string[] tos, string subject, string[]? ccs, string[]? bccs, Content[] contents, Attachment[]? attachments, Status status)
{
Id = id;
From = @from;
Tos = tos;
Subject = subject;
Ccs = ccs;
Bccs = bccs;
Contents = contents;
Attachments = attachments;
Status = status;
}
}
这篇关于.NET 5.0 Web API不适用于具有必需属性的记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!