1

I'm trying to create a very basic login example using an angularjs client and an ASP MVC 6 beta 4 Web Api.

The login call on angular controller side :

    function login() {
        vm.dataLoading = true;
        $http.post('/api/account/login', {
            model: {
                Email: vm.username,
                Password: vm.password,
                RememberMe: vm.rememberMe
            }
        })
            .success(function (data) {
                vm.dataLoading = false;
                if (data.success) {
                    logger.info(data.message);
                    if ($scope.returnToState) {
                        $state.go($scope.returnToState.name, $scope.returnToStateParams);
                    }
                    else {
                        $state.go('dashboard');
                    }
                }
                else {
                    vm.error = data.message;
                }
            })
            .error(function (error) {
                vm.dataLoading = false;
                vm.error = data;
            });
    }

The API entry point :

    [Route("login")]
    [HttpPost]
    public async Task<IActionResult> Login(LoginViewModel model)
        var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
        if (result.Succeeded)
        {
            return Json(new { success = true, message = "Login success !" });
        }
        else
        {
            return Json(new { success = false, message = "Invalid login attempt." });
        }
    } 

The Model :

public class LoginViewModel
{
    public string Email { get; set; }

    public string Password { get; set; }

    public bool RememberMe { get; set; }
}

When i'm reaching the login entry point, the LoginViewModel instance has its members set to null (except for the RememberMe set to false), even if the view model values are well defined before the $http.post call.

Do you know why the serialisation process does not work ? I read that angular js post method use JSON as datatype.

I assume that the Web Api support Json content negociation (according to this post), but maybe I'm wrong and there is some configuration to add in Startup.cs file.

1

1 Answer 1

2
  • I should format json data as :

    $http.post('/api/account/login', {
         Email: vm.username,
         Password: vm.password,
         RememberMe: vm.rememberMe
    })
    
  • I should add [FromBody] directive in the API prototype :

     public async Task<IActionResult> Login([FromBody]LoginViewModel model)
    
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.