下面的代码被简化以显示必要性。我可以知道出了什么问题吗?我似乎无法使用 [FromBody] 属性检索两个参数(在本例中为 A 和 B)。
错误信息是“无法将多个参数(‘A’和‘B’)绑定(bind)到请求的内容”
如果我只有 A 或 B,那完全没问题。
网络 API:
[Route("API/Test"), HttpPost]
public IHttpActionResult Test([FromBody] int A, [FromBody] int B)
客户:
HttpClient client = new HttpClient();
var content = new FormUrlEncodedContent(
new Dictionary<string, string> {
{ "A", "123" },
{ "B", "456" }
});
client.PostAsync("http://localhost/API/Test", content).Result;
最佳答案
我认为 Web Api 不支持多个 [FromBody] 参数。但是您可以使用 Api 模型,将更多参数传递给您的 api 操作。:
public class YourApiModel
{
public int A{ get; set; }
public int B { get; set; }
//...other properties
}
之后,您可以在 API Controller 测试中简单地使用它:
// POST: api/test
public IHttpActionResult Post([FromBody] YourApiModel model)
{
//do something
}
希望对您有所帮助。
关于c# - WebAPI 自托管 : Can't bind multiple parameters to the request's content,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38715230/