I have an angular 2 login form and I am trying to call a JWT Token Controller through an API call.
My user.service.ts is as follows :-
login(username, password) {
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let credentials = JSON.stringify({ username, password });
console.log(username, password);
return this._http.post('http://localhost:5000/api/jwt', credentials, { headers: headers })
.map(res => res.json())
.map((res) => {
if (res.success) {
localStorage.setItem('auth_token', res.auth_token);
this.loggedIn = true;
}
return res.success;
});
}
When I do the console.log(username, password); I am getting the correct username and password entered in the form.
Then I have the Controller as follows :-
[HttpPost]
[AllowAnonymous]
public async Task<IActionResult> Get(string username, string password)
{
//code here
}
My problem is that username and password is always null.
I have tried to do a post with Postman to 'http://localhost:5000/api/jwt' with the username and password and it works fine.
How can I pass the username and password to the controller from the Angular 2 form?
Thanks for your help and time
Johann
You set a wrong Content-Type header, it must be JSON:
headers.append('Content-Type', 'application/json');
Also make sure that you create a valid JSON object (JSON.stringify({ username, password })
is invalid and you are getting a javascript error to the console saying that this is broken):
let credentials = JSON.stringify({ username: username, password: password });
And last but not least introduce a view model to match this structure:
public class LoginViewModel
{
public string Username { get; set; }
public string Password { get; set; }
}
that your controller action will take as parameter:
public async Task<IActionResult> Get(LoginViewModel loginModel)