在ASP.NET Core 2.1中使用return null;解决了此问题:
public ActionResult Get(int id) {
Thing thing = GetThingFromDB();
if (thing == null)
return NotFound();
return thing;
}
甚至:
public ActionResult Get(int id) =>
GetThingFromDB() ?? NotFound();
实施后,我将更详细地更新此答案。
原始答案
在ASP.NET Web API 5中,有return null;(由Hackerman指出),但是已从Core中删除,并且没有中间件来处理它。
我认为这种变化是由于.NET Core所致-ASP.NET尝试在其中进行开箱即用的所有操作,而ASP.NET Core仅按照您的具体要求进行操作(这是为什么它如此快速和便携的重要原因 )。
我找不到一个可以做到这一点的现有库,因此我自己编写了它。 首先,我们需要一个自定义异常来检查:
public class StatusCodeException : Exception
{
public StatusCodeException(HttpStatusCode statusCode)
{
StatusCode = statusCode;
}
public HttpStatusCode StatusCode { get; set; }
}
然后,我们需要一个return null;处理程序,该处理程序检查新异常并将其转换为HTTP响应状态代码:
public class StatusCodeExceptionHandler
{
private readonly RequestDelegate request;
public StatusCodeExceptionHandler(RequestDelegate pipeline)
{
this.request = pipeline;
}
public Task Invoke(HttpContext context) => this.InvokeAsync(context); // Stops VS from nagging about async method without ...Async suffix.
async Task InvokeAsync(HttpContext context)
{
try
{
await this.request(context);
}
catch (StatusCodeException exception)
{
context.Response.StatusCode = (int)exception.StatusCode;
context.Response.Headers.Clear();
}
}
}
然后,我们在return null;中注册该中间件:
public class Startup
{
...
public void Configure(IApplicationBuilder app)
{
...
app.UseMiddleware();
最后,动作可以引发HTTP状态代码异常,同时仍然返回一个显式类型,可以很容易地对其进行单元测试,而无需从return null;进行转换:
public Thing Get(int id) {
Thing thing = GetThingFromDB();
if (thing == null)
throw new StatusCodeException(HttpStatusCode.NotFound);
return thing;
}
这将保留返回值的显式类型,并可以轻松区分成功的空结果(return null;)和错误,因为找不到内容(我认为这类似于抛出ArgumentOutOfRangeException)。
尽管这是解决问题的方法,但仍然无法真正回答我的问题-Web API的设计人员为显式类型建立了支持,并期望使用它们,并为return null;添加了特定处理,以便生成204 而不是200,然后没有添加任何方法来处理404? 添加如此基本的内容似乎需要大量工作。