将对象绑定到 Web API 端点时指定自定义属性名称 [英] Specifying custom property name when binding object to Web API endpoint

查看:16
本文介绍了将对象绑定到 Web API 端点时指定自定义属性名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 .Net Core Web API.当模型属性与请求正文匹配时,它会自动映射模型.例如,如果你有这个类:

I have a .Net Core Web API. It automatically maps models when the model properties match the request body. For example, if you have this class:

public class Package
{
    public string Carrier { get; set; }
    public string TrackingNumber { get; set; }
}

如果请求正文是以下 JSON,它将正确地将其绑定到 POST 端点:

It would correctly bind it to a POST endpoint if the request body is the following JSON:

{
    carrier: "fedex",
    trackingNumber: "123123123"
}

我需要做的是指定要映射的自定义属性.例如,使用上述相同的类,如果 TrackingNumber 作为 tracking_number 出现,我需要能够映射到 JSON.

What I need to do is specify a custom property to map. For example, using the same class above, I need to be able to map to JSON if the TrackingNumber comes in as tracking_number.

我该怎么做?

推荐答案

更改您的包类并为您希望映射到不同 json 字段的每个字段添加 JsonProperty 修饰.

Change your package class and add JsonProperty decoration for each field you wish to map to a different json field.

public class Package
{
    [JsonProperty(PropertyName = "carrier")]
    public string Carrier { get; set; }

    [JsonProperty(PropertyName = "trackingNumber")]
    public string TrackingNumber { get; set; }
}

这篇关于将对象绑定到 Web API 端点时指定自定义属性名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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