You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 11:36:04