我正在遵循tutorial,介绍如何使用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;
});
}
}
答案 0 :(得分:0)
如果您在URL上输入https://localhost:44371/api/users/register,则不会显示某些页面。 为了在这种情况下注册客户端,您将需要使用UserDto作为http正文对该URL进行HTTP POST。
如果您是通过C#调用的
using (var client = new HttpClient())
{
await client.PostAsJsonAsync("https://localhost:44371/api/users/register" , usetDtoObject);
}