WebAPI接收参数一般会定义一个固定的类,但是有时会接收Dictionary<string, object>

例如

public class AddByLoggerArgsModel
{
    public string SourceName { get; set; }
    public string SourceSession { get; set; }
    public string Level { get; set; }
    public string Category { get; set; }
    public string Message { get; set; }
    public Dictionary<string, object> Others { get; set; }
}

注意看属性Others,如果要取数,就变得困难,需要做ContainsKey判定以及类型转换,

更有甚者,Others的object本身又是一个Dictionary<string, object>。


解决方案,使用dynamic

例如数据如下:

{
    "Level": "trace",
    "Message": "",
    "Others": {
        "loc": {
            "longitude": 134,
            "latitude": 32
        },
        "ip": "192.168.1.1",
        "time": "2023-04-13 21:14:13"
    }
}

要需要取得loc.longitude,可以如下做法

首先接收类改一下,Others改为dynamic

public Dictionary<string, dynamic> Others { get; set; }

然后取数

dynamic loc = Others.loc;
if(loc!=null)
{
    // 注意,这里必须是可空对象,如果不可空,且数据loc.longitude不存在,则会抛出异常
    // 当为可空对象时,假如loc.longitude不存在,会得到一个空的longitude
    double? longitude = loc.longitude; 
    double? latitude = loc.latitude;
}