如何将字典参数传递给web-api方法
本文关键字:web-api 方法 参数传递 字典 | 更新日期: 2023-09-27 18:17:14
我在这里读过所有类似的问题,但我不能想出解决方案。我试图调用web-api方法:
[HttpGet]
public SearchViewModel Get(SearchTypes type, string text, [FromUri]Dictionary<string, string> toyParams)
{
//Code here
}
,我想从uri获取最后一个参数。我试着
http://localhost: 39101/# !/搜索/玩具/福克斯?someParameter = 123
和
http://localhost: 39101/# !/搜索/玩具/福克斯? toyParams[0]。key = someParameter& toyParams [0] value = 123
but toyParams Dictionary
总是空的
刚刚发现这里隐含着另一个问题的答案。
它指向的解决方案重定向到ASP中的模型绑定。净的核心。
或者,简短的回答,你只需要写出这样的请求:
http://localhost: 39101/# !/搜索/玩具/福克斯? toyParams [someParameter1] = 123, toyParams [someParameter2] = 456
虽然很晚,但是以下方法可以作为名称/值对返回查询参数this.Url.Request.GetQueryNameValuePairs ()
我有以下Url -http://localhost: 49980/api/MyRestAPI/postSomeData ? = v& d = e
下面是我的方法,写在Web API 2 -
[HttpPost]
public IHttpActionResult SaveDataFromRestToDB(string dataKey) {
var parameters = this.Url.Request.GetQueryNameValuePairs();
//parameters returns KeyValuePair<string, string>[2], containing values passed in Url Query
}
希望这有帮助!!
API方法接受字典作为请求对象。
[HttpPost("test")]
public async Task<IActionResult> TestDictionary(Dictionary<string, List<MyList>> pairs)
{
foreach (var pair in pairs)
{
var a = new
{
Id = pair.Key,
Name = pair.Value.FirstOrDefault().Name,
Age = pair.Value.FirstOrDefault().Age
};
return Ok(a);
}
return NotFound();
}
class MyList
{
string Name { get; set; };
string Age { get; set; };
}
请求测试API的对象。
{
"myid": [
{
"Name": "testName",
"Age": "testAge"
}
]
}
收到响应。
{
"Id": "myid",
"Name": "testName",
"Age": "testAge"
}
一个简单的方法,而不是字典:
//DTO
public class SearchDTO
{
public int MyProperty1 { get; set; }
public int MyProperty2 { get; set; }
public int MyProperty3 { get; set; }
}
其中,MyProperty1
, MyProperty2
, MyProperty3
为需要搜索的参数。
//GET Method
public string Get([FromUri]SearchDTO searchDTO)
{
return "search result";
}
下面是呼叫URL:
http://localhost: 56880/api/价值观? myproperty1 = 1, myproperty2 = 2, myproperty3 = 3