Below is an Asp.net Core WebAPI which returns bad request with Error details as to its param when let's say duplicate a user is trying to register.
public async Task<IActionResult> Register([FromBody] RegisterModel registerModel)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser
{
//TODO: Use Automapper instead of manual binding
UserName = registerModel.Username,
FirstName = registerModel.FirstName,
LastName = registerModel.LastName,
Email = registerModel.Email
};
var identityResult = await this.userManager.CreateAsync(user, registerModel.Password);
if (identityResult.Succeeded)
{
await signInManager.SignInAsync(user, isPersistent: false);
return Ok(GetToken(user));
}
else
{
Console.WriteLine("Errors are : "+ identityResult.Errors);
return BadRequest(identityResult.Errors);
}
}
return BadRequest(ModelState);
The response is being handled at the Angular side as follows:
user.service.ts
register(user: User) {
// let headers = new Headers({ 'Content-Type': 'application/json' });
//var reqHeader = new HttpHeaders({ 'Content-Type': 'application/json'});
const reqHeader = new HttpHeaders().set('Content-Type', 'application/json')
.set('Accept', 'application/json');
//return this.http.post(this.rootUrl + '/api/account/register', body,{headers : reqHeader});
return this.http.post(this.apiUrl+ '/api/account/register', user,{headers : reqHeader});
}
above method being called out in:
register.component.ts
this.userService.register(this.registerForm.value)
.pipe(map((res: Response) => res.json()))
.subscribe(
data => {
this.alertService.success('Registration successful', true);
this.router.navigate(['/login']);
},
(error:HttpErrorResponse) => {
// let validationErrorDictionary = JSON.parse(error.text());
// for (var fieldName in validationErrorDictionary) {
// if (validationErrorDictionary.hasOwnProperty(fieldName)) {
// this.errors.push(validationErrorDictionary[fieldName]);
// }
// }
// this.alertService.errorMsg(this.errors);
console.log(error.error);
});
When I tried to do Postman I get perfect result as below :
Postman Result:
But the same result despite trying multiple code snippet doesn't work out and all it logs 'Bad result' as a response.
Angular Result:
I did notice though the response lies in the network tab.. just short of an idea to process it.
Error Description:
What's missing here? your response will be much appreciated !