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