angularjsasp.net-mvcasp.net-core

MVC controller method not receiving json data from $http post


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 Code

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

        });
};
}]);

Back end c#

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

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.

things I have tried:

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

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.


Solution

  • 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
    }
    

    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.