首页 > 解决方案 > How can I control this response coming from C# backend project?

问题描述

This is my first question here so I am very excited. :)

I am developing a car rental project with C# for backend and Angular for front end. When I try to register a new user with data of an existing user, I get attached response in Postman. The controller in backend sends a Badrequest with a message "User already exists!". I tried to control this at Front End side in Angular. What I would like to do is, just to recognize this error with an IF statement and show this message "User already exists!" on the web page with a toastr service. However, I can not detect it in Angular at all. Can you please help me? How can I take this backend response into control in Angular? Thanks in advance for your help!

Code in Controller:

[HttpPost("register")]
    public ActionResult Register(UserForRegisterDto userForRegisterDto)
    {
        var userExists = _authService.CheckIfUserExists(userForRegisterDto.Email);
        if (!userExists.Success)
        {
            return BadRequest(userExists.Message);
        }

        var registerResult = _authService.Register(userForRegisterDto, userForRegisterDto.Password);
        var result = _authService.CreateAccessToken(registerResult.Data);
        if (result.Success)
        {
            return Ok(result.Data);
        }

        return BadRequest(result.Message);
    }

标签: c#angularpostmanbad-request

解决方案


要从后端返回带有消息的特定响应代码:

return new HttpStatusCodeResult(errorCode, "Message");

确保控制器中的方法是 ActionResult 类型,而不是 ViewResult。


推荐阅读