我正在 Angular 创建一个用户注册表单,这是 ts
import { Component } from '@angular/core';
import { AuthService } from '../_services/auth.service';
@Component({
selector: 'app-registration',
templateUrl: './registration.component.html',
styleUrl: './registration.component.css'
})
export class RegistrationComponent {
form: any = {
email: null,
password: null,
accountType: 1,
name: null,
address: null,
phone: null
};
isSuccessful = false;
isSignUpFailed = false;
errorMessage = '';
constructor(private authService: AuthService) { }
onSubmit(): void {
const { email, password, accountType, name, address, phone } = this.form;
this.authService.register(email, password, accountType, name, address, phone).subscribe({
next: data => {
console.log(data);
this.isSuccessful = true;
this.isSignUpFailed = false;
},
error: err => {
this.errorMessage = err.error.message;
this.isSignUpFailed = true;
}
});
}
}
提交时调用我的 authService 注册方法(如下),该方法应该调用我的 API 上的注册帐户端点
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { AccountType } from '../_classes/AccountType';
import { RegisterRequest } from '../_DTOs/RegisterRequest';
const AUTH_API = 'https://localhost:7033/api/account/';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
@Injectable({
providedIn: 'root',
})
export class AuthService {
constructor(private http: HttpClient) { }
register(email: string, password: string, accountType: AccountType, name: string, address: string, phone: string): Observable<any> {
const request: RegisterRequest = {
email: email,
password: password,
accountType: accountType,
name: name,
address: address,
phone: phone
}
return this.http.post(
AUTH_API + 'register-account',
{
request
},
httpOptions
);
}
}
在我的 AccountController 中设置断点,该方法似乎永远不会被命中。这是控制器
using AML.Server.Interfaces;
using AML.Server.Models;
using Microsoft.AspNetCore.Mvc;
namespace AML.Server.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class AccountController : ControllerBase
{
private readonly IAccountRepository _accountRepository;
public AccountController(IAccountRepository accountRepository)
{
this._accountRepository = accountRepository;
}
[HttpPost]
[Route("register-account")]
public async Task<bool> RegisterAccount(RegisterRequest request)
{
bool success = false;
if (request.Email == "[email protected]")
{
success = true;
}
// Logic going to repo & return success response
return success;
}
}
}
它抛出 400 bad 响应,我在 DevTools 中收到的响应是
{
"type": "https://tools.ietf.org/html/rfc9110#section-15.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"errors": {
"name": [
"The name field is required."
],
"email": [
"The email field is required."
],
"phone": [
"The phone field is required."
],
"address": [
"The address field is required."
],
"password": [
"The password field is required."
]
},
"traceId": "00-ef5889b3c6e2444528b8799e51a3107b-8ca9bab2705e4cc0-00"
}
好像参数没有通过,但我不知道如何解决这个问题。有人有什么想法吗?
编辑 - 其他可能有用的信息
请求负载
{"request":{"email":"[email protected]","password":"testtest","accountType":1,"name":"Jordan Abc","address":"123 Fake Street","phone":"07123456789"}}
注册表html
<app-navbar></app-navbar>
<div class="font-weight-bold">
<h3 class="title-text">Registration</h3>
</div>
<div class="content col-md-12">
<div class="registration-form">
@if (!isSuccessful) {
<form name="form"
(ngSubmit)="f.form.valid && onSubmit()"
#f="ngForm"
novalidate>
<div class="form-group">
<label for="email">Email</label>
<input type="email"
class="form-control"
name="email"
[(ngModel)]="form.email"
required
email
#email="ngModel"
[ngClass]="{ 'is-invalid': f.submitted && email.errors }" />
@if (email.errors && f.submitted) {
<div class="invalid-feedback">
@if (email.errors['required']) {
<div>Email is required</div>
}
@if (email.errors['email']) {
<div>Email must be a valid email address</div>
}
</div>
}
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password"
class="form-control"
name="password"
[(ngModel)]="form.password"
required
minlength="6"
#password="ngModel"
[ngClass]="{ 'is-invalid': f.submitted && password.errors }" />
@if (password.errors && f.submitted) {
<div class="invalid-feedback">
@if (password.errors['required']) {
<div>Password is required</div>
}
@if (password.errors['minlength']) {
<div>Password must be at least 6 characters</div>
}
</div>
}
</div>
<div class="form-group">
<label for="name">Name</label>
<input type="text"
class="form-control"
name="name"
[(ngModel)]="form.name"
required
minlength="1"
maxlength="30"
#name="ngModel"
[ngClass]="{ 'is-invalid': f.submitted && name.errors }" />
@if (name.errors && f.submitted) {
<div class="invalid-feedback">
@if (name.errors['required']) {
<div>Name is required</div>
}
@if (name.errors['minlength']) {
<div>Name is required</div>
}
@if (name.errors['maxlength']) {
<div>Name must be at most 30 characters</div>
}
</div>
}
</div>
<div class="form-group">
<label for="address">Address</label>
<input type="text"
class="form-control"
name="address"
[(ngModel)]="form.address"
required
minlength="1"
maxlength="75"
#address="ngModel"
[ngClass]="{ 'is-invalid': f.submitted && address.errors }" />
@if (address.errors && f.submitted) {
<div class="invalid-feedback">
@if (address.errors['required']) {
<div>Address is required</div>
}
@if (address.errors['minlength']) {
<div>Address is required</div>
}
@if (address.errors['maxlength']) {
<div>Address must be at most 75 characters</div>
}
</div>
}
</div>
<div class="form-group">
<label for="phone">Phone Number</label>
<input type="tel"
class="form-control"
name="phone"
[(ngModel)]="form.phone"
required
pattern="[0-9]{11}"
#phone="ngModel"
[ngClass]="{ 'is-invalid': f.submitted && phone.errors }" />
@if (phone.errors && f.submitted) {
<div class="invalid-feedback">
@if (phone.errors['required']) {
<div>Phone Number is required</div>
}
@if (phone.errors['tel']) {
<div>Valid UK Phone Number is required</div>
}
@if (phone.errors['pattern']) {
<div>Valid UK Phone Number is required (No spaces)</div>
}
</div>
}
</div>
<div class="form-group">
<button class="btn btn-primary btn-block">Register</button>
</div>
@if (f.submitted && isSignUpFailed) {
<div class="alert alert-warning">
Signup failed!<br />{{ errorMessage }}
</div>
}
</form>
} @else {
<div class="alert alert-success">Your registration is successful!</div>
}
</div>
</div>
proxy.conf.js
const { env } = require('process');
const target = env.ASPNETCORE_HTTPS_PORT ? `https://localhost:${env.ASPNETCORE_HTTPS_PORT}` :
env.ASPNETCORE_URLS ? env.ASPNETCORE_URLS.split(';')[0] : 'https://localhost:7033';
const PROXY_CONFIG = [
{
context: [
"/api/*"
],
target,
secure: false,
}
]
module.exports = PROXY_CONFIG;
在您的 ts 文件中,请应用以下更改:
register(email: string, password: string, accountType: AccountType, name: string, address: string, phone: string): Observable<any> {
const request: RegisterRequest = {
email: email,
password: password,
accountType: accountType,
name: name,
address: address,
phone: phone
}
return this.http.post(
AUTH_API + 'register-account',
request,
httpOptions
);
}
您不需要将请求模型包装到
{..}
中,因为它会将其包装到附加模型中(您可以在 json 请求中看到)。
然后按照建议,请创建一个数据模型并将其添加到您的 API 中: 数据模式:
public class RegisterRequest
{
public string Email { get; set; }
public string Password { get; set; }
public string Name{ get; set; }
public string Address { get; set; }
public string Phone { get; set; }
public AccountType AccountType { get; set; }
//public int AccountType { get; set; } // alternative way to test it
}
在您的控制器中:
[HttpPost("register-account")]
public async Task<bool> RegisterAccount(RegisterRequest request)
{
bool success = false;
if (request.Email == "[email protected]")
{
success = true;
}
// Logic going to repo & return success response
return success;
}