MVC Web API,错误:无法绑定多个参数

Tom*_*Tom 13 c# ajax asp.net-mvc jquery asp.net-web-api

传递参数时出错,

"无法绑定多个参数"

这是我的代码

[HttpPost]
public IHttpActionResult GenerateToken([FromBody]string userName, [FromBody]string password)
{
    //...
}
Run Code Online (Sandbox Code Playgroud)

阿贾克斯:

$.ajax({
    cache: false,
    url: 'http://localhost:14980/api/token/GenerateToken',
    type: 'POST',
    contentType: "application/json; charset=utf-8",
    data: { userName: "userName",password:"password" },

    success: function (response) {
    },

    error: function (jqXhr, textStatus, errorThrown) {

        console.log(jqXhr.responseText);
        alert(textStatus + ": " + errorThrown + ": " + jqXhr.responseText + "  " + jqXhr.status);
    },
    complete: function (jqXhr) {

    },
})
Run Code Online (Sandbox Code Playgroud)

Nko*_*osi 33

参考:ASP.NET Web API中的参数绑定 - 使用[FromBody]

最多允许一个参数从消息正文中读取.所以这不起作用:

// Caution: Will not work!    
public HttpResponseMessage Post([FromBody] int id, [FromBody] string name) { ... }
Run Code Online (Sandbox Code Playgroud)

此规则的原因是请求正文可能存储在只能读取一次的非缓冲流中.

强调我的

话虽如此.您需要创建一个模型来存储预期的聚合数据.

public class AuthModel {
    public string userName { get; set; }
    public string password { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

然后更新操作以期望该模型在正文中

[HttpPost]
public IHttpActionResult GenerateToken([FromBody] AuthModel model) {
    string userName = model.userName;
    string password = model.password;
    //...
}
Run Code Online (Sandbox Code Playgroud)

确保正确发送有效负载

var model = { userName: "userName", password: "password" };
$.ajax({
    cache: false,
    url: 'http://localhost:14980/api/token/GenerateToken',
    type: 'POST',
    contentType: "application/json; charset=utf-8",
    data: JSON.stringify(model),
    success: function (response) {
    },

    error: function (jqXhr, textStatus, errorThrown) {

        console.log(jqXhr.responseText);
        alert(textStatus + ": " + errorThrown + ": " + jqXhr.responseText + "  " + jqXhr.status);
    },
    complete: function (jqXhr) {

    },
})
Run Code Online (Sandbox Code Playgroud)