2

I have created a simple login page using ASP.Net Core WebApi and AngularJS. When I POST data to the web api from angularJS using $http, JSON data does not serialize to as expected in Web Api controller.

Here is my ViewModel class in Web API

 public class LoginVM
 {
    [Required]
    public string Username { get; set; }

    [Required]
    public string Password { get; set; }

 }

Web Api Controller method

 [HttpPost]
 [Route("UserLogin")]
 public LoginVM UserLogin(LoginVM loginVM)
 {
        if (loginVM.Username == "Admin" && loginVM.Password == "123")
        {
            return new LoginVM();
        }
        else
        {
            return null;
        }
 }

ConfigureServices method in statup.cs

 public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddMvc()
            .AddJsonOptions(options =>
            {
                options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            });


        services.AddCors(options => options.AddPolicy("AllowAll", p => p.AllowAnyOrigin()));


    }

AngularJS Service

(function () {
'use strict';

app.factory("membershipService", membershipService);

membershipService.$inject = ['$http', '$rootScope', '$log'];

function membershipService($http, $rootScope, $log) {

    var urlHost = "http://localhost:33443";

    function login(user) {
        var url = urlHost + "/user/UserLogin"
        return $http.post(url, user)
        .then(function (result) {
            $log.info(result);
            return result.data;
        }, function (error) {
            $log.info(error);
        }
        );
    };

    return {
        login: login
    };

}

}());

I'm not going to mention AngularJs view and controller code here since user object successfully passes to the AngularJS service in following json format

{username="admin",password="123"}

Unfortunately Json data does not serialize to the LoginVM object in Web Api controller method as expected. Both Username and password fields becomes null.

Appreciate if someone could explain me what I have done wrong in my code

4
  • Are you able to reach the Web API controller method? Are you able to read the data that comes in via loginVM? Commented Sep 21, 2016 at 17:57
  • Did you tested it with Fiddler or Postman? Try it if not. Commented Sep 21, 2016 at 18:06
  • It reaches the controller method. It serialize to a LoginVM object with Username=null and Password=null Commented Sep 21, 2016 at 18:14
  • try to create a object with "Username" and "Password" instead of "username" and "password". I have a project that works without that "AddJsonOptions". Commented Sep 21, 2016 at 18:32

1 Answer 1

1

Try add [FromBody]

         [HttpPost]
     [Route("UserLogin")]
     public LoginVM UserLogin([FromBody]LoginVM loginVM)
     {
            if (loginVM.Username == "Admin" && loginVM.Password == "123")
            {
                return new LoginVM();
            }
            else
            {
                return null;


 }
 }

And change in seervice:

(function () {
'use strict';

app.factory("membershipService", membershipService);

membershipService.$inject = ['$http', '$rootScope', '$log'];

function membershipService($http, $rootScope, $log) {

    var urlHost = "http://localhost:33443";

    function login(user) {
        var url = urlHost + "/user/UserLogin"
        return $http.post(url, { loginVM : user})
        .then(function (result) {
            $log.info(result);
            return result.data;
        }, function (error) {
            $log.info(error);
        }
        );
    };

    return {
        login: login
    };

}

}());

Modelbinder won't bind your view model if passed data will be have a other name that this one catched in controller method (if you use google chrome f12 and check what data is passed in post)

IF this not work try deserialize json from string.

[HttpPost]


    [Route("UserLogin")]
     public LoginVM UserLogin(string loginVM)
     {
    var model = JsonConvert.DeserializeObject<LoginVM >(loginVM); 
            if (model .Username == "Admin" && model .Password == "123")
            {
                return new LoginVM();
            }
            else
            {
                return null;
            }
     }

(function () {
'use strict';

app.factory("membershipService", membershipService);

membershipService.$inject = ['$http', '$rootScope', '$log'];

function membershipService($http, $rootScope, $log) {

    var urlHost = "http://localhost:33443";

    function login(user) {
        var url = urlHost + "/user/UserLogin"
        return $http.post(url, {loginVM: JSON.stringify(user) } )
        .then(function (result) {
            $log.info(result);
            return result.data;
        }, function (error) {
            $log.info(error);
        }
        );
    };

    return {
        login: login
    };

}

}());
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.