.NET API Post方法如何返回自定义400错误而非指定对象?
解决ASP.NET Web API返回自定义错误码及消息的问题
问题原因
你的方法声明返回ClientLoginOut类型,但尝试返回HttpResponseMessage,两者类型不兼容,导致编译器报错CS0029。
解决方案
方法1:修改返回类型为IHttpActionResult(Web API 2及以上推荐)
将方法返回类型改为IHttpActionResult,可以灵活返回成功结果或错误响应,这是Web API 2的标准做法:
[AllowAnonymous] [HttpPost] public IHttpActionResult Post(ClientLogin clientlogin) { // 执行数据查询逻辑 ClientLoginOut loginResult = QueryClientLoginData(clientlogin); if (loginResult == null) // 判断查询是否失败 { var errorObj = new { errorMessage = "Login Invalid" }; return BadRequest(errorObj); // 直接返回400状态码和自定义JSON } return Ok(loginResult); // 成功时返回200状态码和结果对象 }
方法2:抛出HttpResponseException(无需修改返回类型)
如果不想修改方法返回类型,可以通过抛出异常的方式让框架生成错误响应,适用于旧版本Web API:
[AllowAnonymous] [HttpPost] public ClientLoginOut Post(ClientLogin clientlogin) { ClientLoginOut loginResult = QueryClientLoginData(clientlogin); if (loginResult == null) { var errorContent = new StringContent( "{\"errorMessage\":\"Login Invalid\"}", System.Text.Encoding.UTF8, "application/json" ); var errorResponse = new HttpResponseMessage(HttpStatusCode.BadRequest) { Content = errorContent }; throw new HttpResponseException(errorResponse); } return loginResult; }
方法3:使用ActionResult<T>(ASP.NET Core Web API推荐)
如果是ASP.NET Core环境,推荐使用泛型ActionResult<T>,兼顾强类型返回和灵活的错误处理:
[AllowAnonymous] [HttpPost] public ActionResult<ClientLoginOut> Post(ClientLogin clientlogin) { ClientLoginOut loginResult = QueryClientLoginData(clientlogin); if (loginResult == null) { var errorObj = new { errorMessage = "Login Invalid" }; return BadRequest(errorObj); } return loginResult; }
内容的提问来源于stack exchange,提问作者Paulie
相关产品推荐
相关产品推荐

