MVC控制器方法未从$ http帖子接收json数据 [英] MVC controller method not receiving json data from $http post

查看:57
本文介绍了MVC控制器方法未从$ http帖子接收json数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

This might be basic question but I couldn't find where the issue is. I am using .Net Core for by back end and angularJS for front end. below is my code.

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
}

当我调试此程序时,我可以看到有效负载具有电子邮件和密码值,但是无论如何它们都不会传递给控制器​​方法.我可以看到控制器方法被命中,但是值显示为null.

When I debug this I can see that payload is having the email and password values but anyhow they are not getting passed to the controller method. I can see that controller method is being hit but the values show as null.

我尝试过的事情:

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

它们似乎都没有起作用.任何人都面临此类问题或专家意见.

None of them seem to be working. anyone faced this kind of issue or expert opinion please.

关注此帖子 Angular JS不向Web Api发送数据.尚未完全获得批准的答案,或者与我的问题无关.

Followed this post Angular JS Not Sending Data To Web Api . didn't quite get the approved answer or it is not related to my issue.

推荐答案

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

You have to use the [FromBody] attribute with a model parameter.

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]属性告诉模型绑定程序尝试从JSON内容创建模型.

This is because in ASP.NET Core MVC the default content type is application/x-www-form-urlencoded (for handling HTML form data). The [FromBody] attribute tells the model binder to instead try and create the model from JSON content.

这篇关于MVC控制器方法未从$ http帖子接收json数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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