c# - 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);
}
解决方案
要从后端返回带有消息的特定响应代码:
return new HttpStatusCodeResult(errorCode, "Message");
确保控制器中的方法是 ActionResult 类型,而不是 ViewResult。
推荐阅读
- macos - 尝试将 TurboActivate 编译到 MacOS 64 应用程序中 - 为架构 x86_64 获取 E2597 未定义符号:
- c - 在删除指针后打印指针在括号之间打印空
- javascript - removeChild() 只删除一个 li 元素
- google-apps-script - 事件对象值返回未定义的某些国际字符
- swift - SwiftUI 中的 ForEach
- javascript - 解析ffmpeg信息的正则表达式
- css - 如何停止文本转换:大写(s)大写?
- reactjs - ag-grid + react: checkboxSelection 不更新状态
- ruby - 如何避免同一字符串的多次分配?
- forms - 当页面奇数时在字母之间添加空白页