Json problems using Angular2 and Net Core Web Api

299 views Asked by At

I have trouble receiving a request containing JSON on the server side. Somehow, username and password don't get properly mapped to the User object.

So my question is, what am I doing wrong and how do I fix this?

here is the model:

 public class User
    {
        public string username { get; set; }
        public string password { get; set; }
    }

I have a basic login action in my api controller recieving a request:

    [AllowAnonymous]
    [HttpPost("[action]")]
    public ActionResult Login([FromBody] User user)
    {
        if (user.username == null || user.password == null)
            return StatusCode(400);

        string result = _tokenHelper.GenerateToken(user.username);

        return new JsonResult(result);
    }

and an Angular 2 service sending the request

import { Injectable } from '@angular/core';
import { /*HTTP_PROVIDERS, */ Headers } from '@angular/http';
import { AuthHttp } from 'angular2-jwt';

@Injectable()
export class AuthenticationService {

    jwtToken: any;

    constructor(public authHttp: AuthHttp) { }

    //jwtHeader = new Headers({
    //    "Content-Type": "application/json",
    //    "alg": "HS256",
    //    "typ": "JWT"
    //});

    Login(username: string, password: string) {
        this.authHttp.post('/api/login',
            JSON.stringify({
                "username:": username,
                "password:": password
            })
            //,{ headers: this.jwtHeader }
        ).subscribe(data => this.jwtToken = data,
            () => console.log(this.jwtToken));

        return this.jwtToken;
    }

EDIT 1:

I have debugged the program and null User object gets to the action on the server even though I see the request has more or less the right body. Only the parameters are in the wrong order, password being first for some unknown reason.

here you can see that the request actually happens and that it returns 400 in accordance with my control code

1

There are 1 answers

8
hakany On

Could you try to send without doing JSON.stringify in your angular2 method? Stringify send it as a string and not as an json object.

Hope this helps.