gpt4 book ai didi

angularjs - MVC Controller 方法未从 $http post 接收 json 数据

转载 作者:行者123 更新时间:2023-12-05 08:54:15 24 4
gpt4 key购买 nike

这可能是基本问题,但我找不到问题出在哪里。我在后端使用 .Net Core,在前端使用 angularJS。下面是我的代码。

HTML

<div ng-controller="loginController">
<input type="text" ng-model="email"><br />
<input type="text" ng-model="password"><br />
<input type="submit" ng-click="login()">
</div>

AngularJS 代码

app.controller('loginController',['$scope','$http', function (scope, http) {

scope.login = function () {
var req = {
method: 'POST',
url: '/Account/loginInfo',
data: { email: scope.email, password: scope.password },
headers: {
"Content-Type": "application/json"
}
}
http(req)

.then(function successCallback(response) {

}, function errorCallback(response) {

});
};
}]);

后端c#

[HttpPost]
public JsonResult loginInfo(string email, string password)
{
//do something here
}

当我调试它时,我可以看到有效负载具有电子邮件和密码值,但无论如何它们都没有传递给 Controller ​​方法。我可以看到正在调用 Controller 方法,但值显示为空。

我尝试过的事情:

  • 将内容类型设置为“application/x-www-form-urlencoded”
  • 将数据作为 Json 对象传递
  • 将范围值转换为字符串

他们似乎都没有工作。任何人都遇到过这种问题或专家意见。

关注了这篇文章 Angular JS Not Sending Data To Web Api .没有完全得到批准的答案,或者它与我的问题无关。

最佳答案

您必须将 [FromBody] 属性与模型参数一起使用。

public class Credentials
{
public string Email { get; set; }
public string Password { get; set; }
}

public IActionResult Login([FromBody]Credentials creds)
{
// do stuff
}

这是因为在 ASP.NET Core MVC 中,默认的内容类型是 application/x-www-form-urlencoded(用于处理 HTML 表单数据)。 [FromBody] 属性告诉模型绑定(bind)器改为尝试从 JSON 内容创建模型。

关于angularjs - MVC Controller 方法未从 $http post 接收 json 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50548311/

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