我应该在 Web API 2 中将哪种形式的 JSON 与 Dictionary<string,string> 一起使用?

What form of JSON should I use with Dictionary<string,string> in Web API 2?

通常将 JSON 与 C# 模型绑定在 Web 中非常简单 API,但我发现 Dictionary<string, string> 使用它非常困难。

我有一个模型,比如说 Foo,它有 属性 类型 Bar:

public Bar SomeProp { get; set; }

酒吧有简单的字典:

public class Bar
{
    public Dictionary<string, string> SomeDict { get; set; }
}

看起来很简单,当我得到这种对象时 Web API 生成以下 JSON:

"SomeProp": {
              "Bar":       
              {
                "key": "val",
                "key2": "val2"
              }
            }

问题出在反向的东西上。当我尝试在请求中使用相同的 JSON Web API 不会将其绑定到参数模型。

我做错了什么?

我想传输一个带有 属性 "ExcelRanges" 的数据容器,它是一个字典。我没有设法使用字典作为 属性 的目标类型。

作为解决方法,我使用了一个列表,其条目由自定义 class "Range" 组成,具有名称和值 属性:

/// <summary>
///   Container for data that should be written to an Excel file
/// </summary>
public class ExcelData
{    
  public Guid Id { get; set; }
  public List<Range> ExcelRanges { get; set; }
}

public class Range
{
  public string Name { get; set; }

  public List<List<object>> Values { get; set; }
}


[HttpPost]
[Route("Measures")]
public Guid Measures(ExcelData excelData)
{
 ...
}

function execute(site, filteredMeasures) {

    var excelRanges  = [
     { 
      'Name': 'additionalInvestmentEfficiency', 
      'Values': [[1,2],[3,4]] 
     },
     { 
      'Name': 'totalInvestment', 
      'Values': [[10,20],[30,40]]
     }
   ];

    var data = {
      'Id': site.siteId(),
      'ExcelRanges': excelRanges     
    };

    return $.ajax({
      url: routeConfig.exportMeasureDataByUrl,
      type: 'POST',
      contentType: 'application/json',
      processData: false,
      data: JSON.stringify(data),
      headers: appSecurity.getSecurityHeaders()
    }).done(function(downloadId) {
      window.location.href = routeConfig.exportMeasureDataByUrl + '?downloadId=' + downloadId;
    });


  }