我制作了一个简单的角度5水疗中心,带有.net核心2后端api。我试图发送一个POST请求来注册我的用户但由于某种原因它无法在post调用中注入我的有效负载属性导致auth控制器无法从空实例解析dto对象。我希望错误在我的角度代码中,但我检查了官方文档,看不出我做错了什么。下面我将描述我的代码:
PS:由于这么简单的HTTP调用有很多部分,我还在这里包含了项目:download the source code
我的注册组件调用了' authService.register'进行通话的方法:
import { AuthService } from './../_services/auth.service';
import { Component, OnInit, Input, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'app-register',
templateUrl: './register.component.html',
styleUrls: ['./register.component.css']
})
export class RegisterComponent implements OnInit {
model: any = [];
@Input() valuesFromHome: any;
@Output() cancelRegister = new EventEmitter();
constructor(private authService: AuthService) { }
ngOnInit() {
}
register() {
console.log(this.model);
this.authService.register(this.model).subscribe(() => {
console.log('registration successful');
}, error => {
console.log(error);
});
}
cancel() {
this.cancelRegister.emit(false);
console.log('cancelled');
}
}
这是auth.service
import { Http, Headers, RequestOptions, Response } from '@angular/http';
import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';
@Injectable()
export class AuthService {
baseUrl = 'http://localhost:5000/api/auth';
userToken: any;
constructor(private http: Http) { }
login(model: any) {
return this.http.post(this.baseUrl + '/login', model, this.requestOptions()).map((response: Response) => {
const user = response.json();
if (user) {
localStorage.setItem('token', user.tokenString);
this.userToken = user.tokenString;
}
});
}
register(model: any) {
console.log('model before the call', model);
return this.http.post(this.baseUrl + '/register', model, this.requestOptions());
}
private requestOptions() {
const headers = new Headers({'Content-type': 'application/json'});
return new RequestOptions({headers: headers});
}
}
在通话之前发布"模型" log将使用正确的模型执行得很好:
接下来,当我调试我的auth控制器被命中时,当使用邮递员时,数据被插入,但是通过我的SPA它会给出错误' registerDto不能为空'。
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using DatingApp.API.Data;
using DatingApp.API.Dtos;
using DatingApp.API.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
namespace DatingApp.API.Controllers
{
[AllowAnonymous]
[Route("api/[controller]")]
public class AuthController : Controller
{
private readonly IAuthRepository _repository;
private readonly IConfiguration _config;
public AuthController(IAuthRepository repository, IConfiguration config)
{
this._config = config;
this._repository = repository;
}
[HttpPost("register")]
public async Task<IActionResult> Register([FromBody] userForRegisterDto registerDto)
{
registerDto.Username = registerDto.Username.ToLower();
if (await _repository.UserExists(registerDto.Username))
{
ModelState.AddModelError("Username", "USername already exists");
}
if (!ModelState.IsValid)
return BadRequest(ModelState);
var userToCreate = new User
{
UserName = registerDto.Username
};
var createUser = await _repository.Register(userToCreate, registerDto.Password);
return StatusCode(201);
}
[HttpPost("login")]
public async Task<IActionResult> Login([FromBody] UserForLoginDto userForLoginDto)
{
var userFromRepo = await _repository.Login(userForLoginDto.UserName.ToLower(), userForLoginDto.Password);
if (userFromRepo == null)
{
return Unauthorized();
}
// generate token
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(_config.GetSection("AppSettings:Token").Value);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[] {
new Claim(ClaimTypes.NameIdentifier, userFromRepo.Id.ToString()),
new Claim(ClaimTypes.Name, userFromRepo.UserName)
}),
Expires = DateTime.Now.AddDays(1),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key),
SecurityAlgorithms.HmacSha512)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
var tokenString = tokenHandler.WriteToken(token);
return Ok(new { tokenString });
}
}
}
userForRegisterDto
using System.ComponentModel.DataAnnotations;
namespace DatingApp.API.Dtos
{
public class userForRegisterDto
{
[Required]
public string Username { get; set; }
[Required]
[StringLength(8, MinimumLength = 4, ErrorMessage = "You must specify a password between 4 and 8 characters")]
public string Password { get; set; }
}
}
我检查了Angular文档,所有参数都匹配。文档可以在这里找到: https://angular.io/guide/http
模特:
namespace DatingApp.API.Models
{
public class User
{
public int Id { get; set; }
public string UserName { get; set; }
public byte[] PasswordHash { get; set; }
public byte[] PasswordSalt { get; set; }
}
}
答案 0 :(得分:2)
尝试
将
model:any = []
替换为model:any = {}
;
您创建的数组不是对象。