我使用 C# 9.0record类型作为 .NET 5.0 Web API 项目的绑定模型。某些属性是必需的。
我正在使用record位置语法,但收到错误。
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
);
Run Code Online (Sandbox Code Playgroud)
然后将其公开为我的Index操作的绑定模型:
public async Task<ActionResult> Index(Service.Models.Mail mailRequest)
{
…
}
Run Code Online (Sandbox Code Playgroud)
但是,每当我尝试发出请求时,都会收到以下错误:
记录类型“Service.Models.Mail”在属性“Contents”上定义了将被忽略的验证元数据。“内容”是记录主构造函数中的一个参数,验证元数据必须与构造函数参数相关联。
我尝试删除该属性上的Contents属性,但是对于下一个(先前的)属性它失败了。我尝试使用[param: …]而不是[property: …],以及混合它们,但不断收到相同类型的错误。
我环顾了网络,并没有发现任何针对 C# 9 记录以不同方式处理注释的建议。我尽力了,但我没有想法——除了将我的记录转换为 POCO。
使用 C# 9 中的新 C# 记录类型,我想知道是否可以(用于序列化)JsonPropertyAttribute在构造函数参数上设置from Newtonsoft.Json。它似乎不是开箱即用的。
MWE:
using System;
using Newtonsoft.Json;
Console.WriteLine(JsonConvert.SerializeObject(new Something("something")));
record Something([JsonProperty("hello")] string world) {}
Run Code Online (Sandbox Code Playgroud)
输出:
{"world":"something"}
Run Code Online (Sandbox Code Playgroud)
预期输出:
{"hello":"something"}
Run Code Online (Sandbox Code Playgroud)
有没有一种简单的方法可以让它像这样工作?还是我们必须使用真正的构造函数恢复到属性样式?
internal record Something
{
public Something(string world) { World = world; }
[JsonProperty("hello")] public string World { get; }
}
Run Code Online (Sandbox Code Playgroud) 我想使用带有 JsonPropertyName 属性的记录,但它导致了错误。这个不支持?任何解决方法?
public record QuoteResponse([JsonPropertyName("quotes")] IReadOnlyCollection<Quote>? Quotes);
Error CS0592 Attribute 'JsonPropertyName' is not valid on this declaration type. It is only valid on 'property, indexer, field' declarations.
Run Code Online (Sandbox Code Playgroud)
感谢审稿人找到重复内容:How do I target attribute for a record class?
.NET 5.0 Web API不适用于具有所需属性的记录也与之相关。
我试图理解为什么 3. 位置记录属性在下面不起作用。
这是一个新的 ASP.NET Core Razor Pages Web 应用程序,其源代码位于https://github.com/djhmateer/record-test
https://daveabrock.com/2020/11/18/simplify-api-models-with-records似乎已经让它与 API 一起使用。
public class LoginModelNRTB : PageModel
{
[BindProperty]
// there will never be an InputModel on get
// but if we set to nullable InputModel then the cshtml will produce dereference warnings
// https://stackoverflow.com/a/54973095/26086
// so this will get rid of the warnings as we are happy we will never …Run Code Online (Sandbox Code Playgroud)