MVC Web API,错误:无法绑定多个参数 [英] MVC Web API, Error: Can't bind multiple parameters

查看:394
本文介绍了MVC Web API,错误:无法绑定多个参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

传递参数时出现错误

无法绑定多个参数"

"Can't bind multiple parameters"

这是我的代码

[HttpPost]
public IHttpActionResult GenerateToken([FromBody]string userName, [FromBody]string password)
{
    //...
}

Ajax:

$.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) {

    },
})

推荐答案

参考:

最多允许从邮件正文读取一个参数.所以 这将不起作用:

At most one parameter is allowed to read from the message body. So this will not work:

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

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

The reason for this rule is that the request body might be stored in a non-buffered stream that can only be read once.

强调我的

emphasis mine

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

That being said. You need create a model to store the expected aggregated data.

public class AuthModel {
    public string userName { get; set; }
    public string password { get; set; }
}

然后更新操作以期望体内具有该模型

and then update action to expect that model in the body

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

确保正确发送有效载荷

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) {

    },
})

这篇关于MVC Web API,错误:无法绑定多个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆