【发布时间】:2022-12-28 19:56:48
【问题描述】:
我在考虑如何正确处理集合的返回码
如果您只有一个值(POCO/模型)——没问题,如果有时您需要返回Http-204。例如,在登录期间。你只要做
if (model == null)
return NoContent();
return Ok(model);
我看到这篇文章 --https://weblog.west-wind.com/posts/2020/Feb/24/Null-API-Responses-and-HTTP-204-Results-in-ASPNET-Core
比方说,您有一个系统,对于集合,“提供者”总是返回非物化的IEnumerable<T>。还有点return Ok(result)不知道有没有内容。唯一知道的方法是致电.ToList(),获取Count并就此做出决定。这是我想将有效的空结果作为Http-204代码处理的时候
我理解,作者在文章中的立场是空集合仍然应该返回200。
这是普遍接受的行为或意见吗?
否则,只要我没有 null 来自 provider.Get(..) 电话,我就可以安全地返回格式正确的 (application/json) '200' 响应。
当我需要提前知道项目计数时是否存在任何性能影响问题,如果我在返回Ok或NoContent之前通过调用ToList()实现IEnumerable<T>?
【问题讨论】:
标签: rest asp.net-core asp.net-web-api .net-6.0