Home > Blockchain >  Login/Register using .net
Login/Register using .net

Time:11-22

I am trying to get working my login/register methods in angular with using .net as backend.

My controller in c#:

    [HttpPost]
    [Route("Register")]
    public async Task<IActionResult> Register(string email, string password)
    {
        if (ModelState.IsValid)
        {
            var user = new User() {UserName = email, Email = email};
            var result = await _userManager.CreateAsync(user, password);
            if (result.Succeeded)
            {
                return Ok();
            }
        }

        return BadRequest();
    }

So I want to pass 2 values to request: email and password. Route to that method is: https://localhost:44331/users/Register

This is how my user service looks like in angular:

export class UserService {
  readonly ApiUrl = "https://localhost:44331/users"
  constructor(private http: HttpClient) { }

  LogIn(email:any, password:any){
    return this.http.post(this.ApiUrl   '/Login', email, password);
  }
  Register(email:any, password:any){
    return this.http.post(this.ApiUrl   '/Register', email, password);
  }
}

Register component.ts:

export class RegisterComponent implements OnInit {
  userForm! : FormGroup;
  subbmited = false;
  constructor(private formBuilder: FormBuilder, private userService: UserService) { }

  ngOnInit(){
    this.userForm = this.formBuilder.group({
      email: new FormControl(['', Validators.required, Validators.email]),
      password: new FormControl(['', Validators.required, Validators.minLength(6)])
    })
  }

  get Email(){
    return this.userForm.get('email');
  }
  get Password(){
    return this.userForm.get('password');
  }

  onSubmit(){
    this.subbmited = true;
    if(this.userForm.invalid){
      return;
    }
    this.userService.Register(this.Email?.value, this.Password?.value);
    alert('SUCCESS!! :-)\n\n'   JSON.stringify(this.userForm.value))
  }

}

And part of my register html:

<form [formGroup]="userForm" (ngSubmit)="onSubmit()">
      <h1 >Please sign in</h1>
      <div >
      <label for="inputEmail" >Email address</label>
      <input type="email" id="email" formControlName="email"  placeholder="Email address" required autofocus>
      </div>
      <div >
      <label for="inputPassword" >Password</label>
      <input type="password" id="password" formControlName="password"  placeholder="Password" required>
    </div>
    <div >
      <button  type="submit">Sign in</button>
    </div>
    </form>

enter image description here

And this is how it looks in browser. It always auto fill those inputs with this text.

But the real problem is that my request never reaches my backend. Or at least I think so. It doesn't show any errors in console, when I change route to one with typo (like https://localhost:44331/userrsrss/Register) it still doesn't throw any errors. That is kinda weird to me since i get alert about successful registration from alert with proper values. Tried to debug it and this is how values looks like while using post:

enter image description here

I am total amateur when it comes to angular and just started to learning it. What is wrong with my code?

CodePudding user response:

Because your body is just the email, and your password here is considered as options
you should first create an interface for your Login model and use it as a body in your post request

Login-model.ts

export interface LoginModel {
  UserName: string;
  Password: string;
} 

HTTP post

LogIn(loginModel: LoginModel){
    return this.http.post(this.ApiUrl   '/Login', loginModel, this.generateHeaders());
  }

private generateHeaders = () => {
    return {
      headers: new HttpHeaders({
        "Content-Type": "application/json",
      }),
    };
  };  

And you have to modify backend code to receive a model as well instead of two strings.
You can also have a look at this article and its other parts to implement authentication with Angular correctly.

  • Related