英文:
return a Tuple from minimal API
问题
我试图在最小API中返回一个元组,问题归结如下:
app.MapPost("/colorkeyrect", () => server.ColorkeyRect());
public (int x, int y, int w, int h) ColorkeyRect()
{
return (10, 10, 10, 10);
}
但通过网络发送的数据是一个空的 JSON:
content = await response.Content.ReadAsStringAsync();
> '{}'
var obj = JsonConvert.DeserializeObject<(int, int, int, int)>(content);
因此,结果变成了(0, 0, 0, 0),而不是(10, 10, 10, 10)。
在最小API应用中返回一个元组是否可能?
当仅依赖基本类型时,该怎么做才能获得一个有效的返回对象?
英文:
I'm trying to return a Tuple in a minimal API, it boils down to this:
app.MapPost("/colorkeyrect", () => server.ColorkeyRect());
public (int x, int y, int w, int h) ColorkeyRect()
{
return (10, 10, 10, 10);
}
But the data that is sent over the wire is an empty json:
content = await response.Content.ReadAsStringAsync();
> '{}'
var obj = JsonConvert.DeserializeObject<(int, int, int, int)>(content);
So this becomes (0, 0, 0, 0) instead of (10, 10, 10, 10).
Is it even possible to return a Tuple in a Minimal API app?
What to do to get a valid object returned when only relying on primitive types?
答案1
得分: 2
是的,这是可能的。默认情况下,System.Text.Json 不会序列化字段,而值元组的元素是字段([`ValueTuple`][1]),所以你需要配置 `JsonOptions`(确保使用“正确”的选项 - 对于来自 `Microsoft.AspNetCore.Http.Json` 命名空间的 Minimal APIs):
```csharp
builder.Services.Configure<JsonOptions>(options => options.SerializerOptions.IncludeFields = true);
但我认为这有点没用,值元组的名称是一些在运行时不表示的信息,所以你会得到这样的响应:
{"item1":1,"item2":2}
我建议要么使用匿名类型,要么只是创建一个 record
(如果确实需要,则是 record struct
),现在很容易创建新的 DTO 类型。而且使用目标类型化的新表达式也不会在方法中带来太大变化:
record Responce(int X, int Y, int W, int H); // 或者 record struct Responce ...
public Responce ColorkeyRect()
{
return new (10, 10, 10, 10);
}
<details>
<summary>英文:</summary>
Yes, it is possible. By default System.Text.Json does not serialize fields, and value tuple elements are fields ([`ValueTuple`][1]), so you need to configure `JsonOptions` (be sure to use "correct" ones - for Minimal APIs from `Microsoft.AspNetCore.Http.Json` namespace):
```csharp
builder.Services.Configure<JsonOptions>(options => options.SerializerOptions.IncludeFields = true);
But I would argue that it is a bit useless, value tuple names is a piece of information which is not represented at runtime so you will get response like:
{"item1":1,"item2":2}
I would recommend to use either anonymous type or just create a record
(record struct
if really needed), it is very easy to create a new DTO type nowadays. And with target-typed new expressions it is not a big change in the method also:
record Responce(int X, int Y, int W, int H); // or record struct Responce ...
public Responce ColorkeyRect()
{
return new (10, 10, 10, 10);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论