gpt4 book ai didi

c# - MVC 网络 API,错误 : Can't bind multiple parameters

转载 作者:可可西里 更新时间:2023-11-01 08:02:21 25 4
gpt4 key购买 nike

传递参数时出错,

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

},
})

最佳答案

引用:Parameter Binding in ASP.NET Web API - Using [FromBody]

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.

强调我的

话虽这么说。您需要创建一个模型来存储预期的聚合数据。

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

然后更新 Action 以期望 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) {

},
})

关于c# - MVC 网络 API,错误 : Can't bind multiple parameters,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44599041/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com