【问题标题】:How to return custom error messages in dotnet core Web Api如何在 dotnet core Web Api 中返回自定义错误消息
【发布时间】:2021-11-27 12:26:54
【问题描述】:

我正在使用 dot net core 编写一个 web api。当用户输入和我想要返回的无效用户名或密码、作为 json 响应的无效用户名或密码时,该功能很简单。我如何在 dot net core 中做到这一点,我已经设法返回了这个

用户名或密码无效

我怎样才能改为返回这个

{ "message": "Invalid Login credentials!" }

这是我的控制器

  [HttpPost]
            [Route("/api/[controller]/signin")]
            public async Task<IActionResult> Login([FromBody] LoginViewModel loginmodel)
            {
                if (!ModelState.IsValid)
                {
                    //return BadRequestModelState();
                    return Conflict(new ErrorViewModel("Wrong data sent"));
                }
    
    
                Users user = await _userService.GetByEmail(loginmodel.Username);
                if (user == null)
                {
                   
                    return this.StatusCode(StatusCodes.Status401Unauthorized, "Invalid username or password");
                }
    
                bool isCorrectPassword = _passwordHasher.VerifyPassword(loginmodel.Password, user.Password);
                if (!isCorrectPassword)
                {
                    return this.StatusCode(StatusCodes.Status401Unauthorized, "Invalid username or password");
                }
}

【问题讨论】:

    标签: c# .net-core asp.net-core-webapi


    【解决方案1】:

    最简单的方法之一

    return StatusCode(StatusCodes.Status401Unauthorized, new { message = "Invalid username or password" });
    

    【讨论】:

      猜你喜欢
      • 2020-09-07
      • 1970-01-01
      • 2017-09-25
      • 2014-05-01
      • 1970-01-01
      • 2020-05-29
      • 2018-08-13
      • 2019-08-11
      • 2021-10-19
      相关资源
      最近更新 更多