c# - WebAPI 自托管 : Can't bind multiple parameters to the request's content

标签 c# asp.net-web-api

下面的代码被简化以显示必要性。我可以知道出了什么问题吗?我似乎无法使用 [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/

相关文章:

c# - 如何将 wpf 的图像源属性设置为 Canvas 而不是图像 url?

c# - 在表单中接受用户输入

c# - 将事件绑定(bind)到 Item ViewModel

iis - Microsoft.Owin.Host.SystemWeb 和 Microsoft.AspNet.WebApi.WebHost nuget 包之间的区别

c# - Web API 路由 - 找到多个与请求匹配的操作

rest - 使用具有基本身份验证的 Fiddler 访问 RESTful WebAPI

c# - 线程在哪里结束?

c# - 如何保护 ASP.NET Web API

asp.net-web-api - Veracode 问题 CWE 915

asp.net-web-api - 使用 Autofac 将 NLog 注入(inject) Web Api Controller