首页 > 解决方案 > 使用 Angular 7 和 core 2.1 注册用户

问题描述

我正在关注如何使用 angular 7 和真正的 net core 2.1 IIS Express 服务器注册用户的教程。

我尝试在客户端网站上注册后收到此错误:

POST https://localhost:44371/api/users/register 404

这是服务器控制器用户:(其余代码在上面的链接中)

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();
    }
  }
}

我可以访问默认值页面。如何显示用户页面?
当我输入https://localhost:44371/api/users时,我得到一个 404。

这是角度代码:

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;
            });
}
}

标签: c#.net-core

解决方案


如果您在 URL 上键入https://localhost:44371/api/users/register,您将不会看到某些页面。为了在这种情况下注册客户端,您需要对该 URL 执行 HTTP POST,并将 UserDto 作为 http 正文。

如果你从 C# 调用它

using (var client = new HttpClient())
{
     await client.PostAsJsonAsync("https://localhost:44371/api/users/register" , usetDtoObject);
}

推荐阅读