ASP.NET Core 2.2
DictionaryModelBinder

[HttpGet("{id}", Name = "GetValue")]
public async Task<IActionResult> GetValue(
[ModelBinder(BinderType=typeof(DictionaryModelBinder<string,string>))]
    IDictionary<string, string> id)
{
     return Ok();
}


错误:


InvalidOperationException:接受所有给定的多个构造函数
在类型中找到了参数类型
'Microsoft.AspNetCore.Mvc.ModelBinding.Binders.DictionaryModelBinder`2 [System.String,System.String]'。
应该只有一个适用的构造函数。

最佳答案

经过一些源代码分析,我找到了使用DictionaryModelBinder的方法。

[HttpGet("GetValue")]
public async Task<IActionResult> GetValue([FromQuery] IDictionary<string, string> id)
{
     return Ok();
}


并且请求应为api/GetValue?id.Key1=Value1&id.Key2=Value2&id.Key3=Value3(或)api/values?Values[Key1]=Value1&Values[Key2]=Value2&Values[Key3]=Value3

注意


无需显式使用ModelBinderAttribute。默认情况下添加
我们需要为参数添加FromQueryAttribute

09-30 17:42
查看更多