所以我一直在学习一些 .net 核心,我正在用它构建一个 API。通常我会使用 angular 并在那里发送请求。
我有以下 Angular 片段:
//The data I need to send.
$scope.PersonalInfo = {
firstName: '',
lastName: '',
companyName: '',
email: '',
password: '',
confirmPassword: '',
imageLink: ''
};
然后是相同数据的后端模型:
public class UserProfileModel
{
public string userID { get; set; }
public string firstName { get; set; }
public string lastName { get; set; }
public string companyName { get; set; }
public string email { get; set; }
public string password { get; set; }
public string confirmPassword { get; set; }
public string imageLink { get; set; }
}
最后是应该发送它的方法:
$scope.UpdateProfile = function () {
var profile = JSON.stringify($scope.PersonalInfo);
$http.post('/api/Profile/Users', profile).then(function (response) {
debugger;
$log.log(profile);
$log.log(response);
});
};
无论我做了多少更改(将数据作为字符串化的 JSON 发送,或发送作用域对象),当请求到达 Controller 时,我最终得到的是:
$scope.PersonalInfo 在发送请求之前充满了数据。
非常感谢任何帮助。提前致谢。
最佳答案
您需要在 post 调用中提及 [FromBody] 属性。像这样,
[HttpPost]
[Route("api/bar/users")]
public IActionResult Users([FromBody]UserProfileViewModel profile)
{
return Json(new { Data = profile });
}
应该可以了。
必须使用 FromBody
属性,以便框架可以使用正确的 input formatter
来建模绑定(bind)。例如,内容类型 application/json 使用的默认格式化程序是基于 Json.Net 的 JSON 格式化程序
详细信息:https://learn.microsoft.com/en-us/aspnet/core/mvc/models/model-binding
关于javascript - 具有.net核心模型的AngularJS未绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43742830/