如何在.NET Core Web API中返回自定义JSON格式错误消息
解决方案
你当前返回纯文本是因为StatusCode方法第二个参数传入的是字符串类型,.NET Core会默认返回text/plain类型的响应。只需要将第二个参数替换为对应结构的对象,框架就会自动序列化为你需要的JSON格式。
方案1:直接使用匿名对象(最快捷,无需额外定义类)
直接修改两处返回401的代码即可:
// 用户不存在时 return this.StatusCode(StatusCodes.Status401Unauthorized, new { message = "Invalid Login credentials!" }); // 密码错误时 return this.StatusCode(StatusCodes.Status401Unauthorized, new { message = "Invalid Login credentials!" });
修改完后接口就会返回你要求的JSON结构,响应头Content-Type也会自动设置为application/json。
方案2:定义统一错误响应模型(适合项目全局复用)
如果你的项目多个接口都需要返回相同结构的错误提示,可以先定义一个通用的响应类:
public class CommonErrorResult { public string message { get; set; } }
之后返回的时候直接实例化这个类即可:
return this.StatusCode(StatusCodes.Status401Unauthorized, new CommonErrorResult { message = "Invalid Login credentials!" });
修改后的完整控制器代码示例
[HttpPost] [Route("/api/[controller]/signin")] public async Task<IActionResult> Login([FromBody] LoginViewModel loginmodel) { if (!ModelState.IsValid) { return Conflict(new ErrorViewModel("Wrong data sent")); } Users user = await _userService.GetByEmail(loginmodel.Username); if (user == null) { return this.StatusCode(StatusCodes.Status401Unauthorized, new { message = "Invalid Login credentials!" }); } bool isCorrectPassword = _passwordHasher.VerifyPassword(loginmodel.Password, user.Password); if (!isCorrectPassword) { return this.StatusCode(StatusCodes.Status401Unauthorized, new { message = "Invalid Login credentials!" }); } // 此处补充登录成功后的业务逻辑 }
内容的提问来源于stack exchange,提问作者arriff
相关产品推荐
相关产品推荐

