值元组从WebAPI公开了错误的参数名称 [英] Value tuples expose wrong parameter name from WebAPI

查看:64
本文介绍了值元组从WebAPI公开了错误的参数名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Web API.我有点懒,决定从控制器返回一个值元组.

I'm using web api. I've been a bit lazy and decided to return a value tuple from my controller.

[HttpGet]
[Route(AuthAPIRoutes.GET_MFA_DEVICES)]
public (string Type, string Value)[] GetMultiFactoryMethods()
{
    return GlobalFactory<IPaystreamMFASecurityService>.Instance.GetMultiFactorMethods();
}

JSON响应似乎没有使用适当的命名方式吗?

The JSON response doesn't seem to be using the appropriate naming is this being optimized away?

{
    "item1": "Phone",
    "item2": "1-512-555-0550"
}

注意::我知道我可以明确创建模型来避免此问题.我想了解发生了什么,为什么在响应中不尊重我的值元组名称?

NOTE: I'm aware I can explicitly make a model to avoid this problem. I would like to understand what is occurring and why aren't my value tuple names being respected in the response?

推荐答案

正在发生的事情是

What is occurring is that ValueTuple as a type (a group of generic types, actually) is actually very static, and has properties named things like Item1, Item2, etc.

从C#中获得的不错的语法,您可以在其中声明名称并在代码中的其他位置使用该名称,这只是C#语言的功能.通过名称引用这些值的已编译代码最终调用了那些静态属性(例如, Item1 ).实际上,您仍然可以通过自己的C#代码中的项目"名称访问这些属性.

The nice syntax you get from C# where you can declare a name and have it used elsewhere in your code is simply a feature of the C# language. The compiled code referencing those values by name ends up calling into those static properties (Item1, e.g.). And in fact, you can still access those properties by their "Item" names in your own C# code.

从编译代码的角度来看,有关这些元组上字段名称的唯一线索是与方法相关联的属性,因此,除非ASP.NET传递有关action方法的上下文信息进入序列化程序,序列化程序将无法知道这些属性应具有的名称.

From the compiled code's perspective, the only clue about the names of the fields on those tuples is an attribute that gets associated with the method, so unless ASP.NET passed contextual information about the action method into the serializer, there would be no way for the serializer to know what names those properties were supposed to have.

请参阅本文以深入了解内容ValueTuples在后台进行操作.

See this article for an in-depth look at what ValueTuples are doing under the hood.

这篇关于值元组从WebAPI公开了错误的参数名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆