参考:ASP.NET Web API中的参数绑定-使用[FromBody]
最多允许一个参数从消息正文中读取。 因此,这将不起作用:
// Caution: Will not work! public HttpResponseMessage Post([FromBody] int id, [FromBody] stringname) { … }
此规则的原因是请求正文可能存储在只能读取一次的非缓冲流中。
重点矿
话虽如此。您需要创建一个模型来存储预期的聚合数据。
public class AuthModel { public string userName { get; set; } public string password { get; set; }}然后更新动作以期望模型在体内
[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) { },})


