locked
Register user using the Users Controller RRS feed

  • Question

  • User-2004102533 posted

    I am working on a tutorial on registering and logging users .  I get a 404 after I register a new user from the  angular client and when I attempt to display

    https://localhost:44371/api/users

    Here is the users controller code:

    using System;
    using System.Collections.Generic;
    using Microsoft.AspNetCore.Mvc;
    using AutoMapper;
    using System.IdentityModel.Tokens.Jwt;
    using RegisterLogin.Helpers;
    using Microsoft.Extensions.Options;
    using System.Text;
    using Microsoft.IdentityModel.Tokens;
    using System.Security.Claims;
    using Microsoft.AspNetCore.Authorization;
    using RegisterLogin.Services;
    using RegisterLogin.Dtos;
    using RegisterLogin.Entities;
    
    namespace RegisterLogin.Controllers
    {
        [Authorize]
        [ApiController]
        [Route("[controller]")]
        public class UsersController : ControllerBase
        {
            private IUserService _userService;
            private IMapper _mapper;
            private readonly AppSettings _appSettings;
    
            public UsersController(
                IUserService userService,
                IMapper mapper,
                IOptions<AppSettings> appSettings)
            {
                _userService = userService;
                _mapper = mapper;
                _appSettings = appSettings.Value;
            }
    
            [AllowAnonymous]
            [HttpPost("authenticate")]
            public IActionResult Authenticate([FromBody]UserDto userDto)
            {
                var user = _userService.Authenticate(userDto.Username, userDto.Password);
    
                if (user == null)
                    return BadRequest(new { message = "Username or password is incorrect" });
    
                var tokenHandler = new JwtSecurityTokenHandler();
                var key = Encoding.ASCII.GetBytes(_appSettings.Secret);
                var tokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject = new ClaimsIdentity(new Claim[]
                    {
                        new Claim(ClaimTypes.Name, user.Id.ToString())
                    }),
                    Expires = DateTime.UtcNow.AddDays(7),
                    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
                };
                var token = tokenHandler.CreateToken(tokenDescriptor);
                var tokenString = tokenHandler.WriteToken(token);
    
                // return basic user info (without password) and token to store client side
                return Ok(new
                {
                    Id = user.Id,
                    Username = user.Username,
                    FirstName = user.FirstName,
                    LastName = user.LastName,
                    Token = tokenString
                });
            }
    
            [AllowAnonymous]
            [HttpPost("register")]
            public IActionResult Register([FromBody]UserDto userDto)
            {
                // map dto to entity
                var user = _mapper.Map<User>(userDto);
    
                try
                {
                    // save 
                    _userService.Create(user, userDto.Password);
                    return Ok();
                }
                catch (AppException ex)
                {
                    // return error message if there was an exception
                    return BadRequest(new { message = ex.Message });
                }
            }
    
            [HttpGet]
            public IActionResult GetAll()
            {
                var users = _userService.GetAll();
                var userDtos = _mapper.Map<IList<UserDto>>(users);
                return Ok(userDtos);
            }
    
            [HttpGet("{id}")]
            public IActionResult GetById(int id)
            {
                var user = _userService.GetById(id);
                var userDto = _mapper.Map<UserDto>(user);
                return Ok(userDto);
            }
    
            [HttpPut("{id}")]
            public IActionResult Update(int id, [FromBody]UserDto userDto)
            {
                // map dto to entity and set id
                var user = _mapper.Map<User>(userDto);
                user.Id = id;
    
                try
                {
                    // save 
                    _userService.Update(user, userDto.Password);
                    return Ok();
                }
                catch (AppException ex)
                {
                    // return error message if there was an exception
                    return BadRequest(new { message = ex.Message });
                }
            }
    
            [HttpDelete("{id}")]
            public IActionResult Delete(int id)
            {
                _userService.Delete(id);
                return Ok();
            }
        }
    }
    

    Here is the typescript from angular

    import { Component, OnInit } from '@angular/core';
    import { Router } from '@angular/router';
    import { FormBuilder, FormGroup, Validators } from '@angular/forms';
    import { first } from 'rxjs/operators';
    
    import { AlertService, UserService, AuthenticationService } from '../_services';
    
    @Component({templateUrl: 'register.component.html'})
    export class RegisterComponent implements OnInit {
        registerForm: FormGroup;
        loading = false;
        submitted = false;
    
        constructor(
            private formBuilder: FormBuilder,
            private router: Router,
            private authenticationService: AuthenticationService,
            private userService: UserService,
            private alertService: AlertService
        ) { 
            // redirect to home if already logged in
            if (this.authenticationService.currentUserValue) { 
                this.router.navigate(['/']);
            }
        }
    
        ngOnInit() {
            this.registerForm = this.formBuilder.group({
                firstName: ['', Validators.required],
                lastName: ['', Validators.required],
                username: ['', Validators.required],
                password: ['', [Validators.required, Validators.minLength(6)]]
            });
        }
    
        // convenience getter for easy access to form fields
        get f() { return this.registerForm.controls; }
    
        onSubmit() {
            this.submitted = true;
    
            // stop here if form is invalid
            if (this.registerForm.invalid) {
                return;
            }
    
            this.loading = true;
            this.userService.register(this.registerForm.value)
                .pipe(first())
                .subscribe(
                    data => {
                        this.alertService.success('Registration successful', true);
                        this.router.navigate(['/login']);
                    },
                    error => {
                        this.alertService.error(error);
                        this.loading = false;
                    });
        }
    }
    

    Friday, December 14, 2018 5:21 PM

Answers

  • User-2004102533 posted

    I found the error,  I needed to change to "api/[controller]" in the users controller from "[controller]" it works now.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, December 14, 2018 6:22 PM