【问题标题】:How to handle the $filter query GET operation and show Status Code 204 for get request for which data doesn't exist如何处理 $filter 查询 GET 操作并为不存在数据的获取请求显示状态代码 204
【发布时间】:2026-02-08 01:55:02
【问题描述】:

我正在发送以下带有过滤查询的 GET URI,该查询返回 emapty 值,例如“Value”:[]。

https://localhost:44372/api/V1/Customers?$filter=CustomerName eq 'NTPC'

但我的要求是,将响应正文显示为空意味着响应正文中不应出现任何内容,并且状态代码应显示204 No Content

我需要在哪里处理获取请求以显示 204(无内容)状态代码。

提前谢谢....

【问题讨论】:

    标签: rest asp.net-web-api asp.net-web-api2 odata restful-url


    【解决方案1】:

    假设您有一个 CustomersController,并且您调用的方法返回 HttpResponseMessage,您可以像这样简单地使用 Request.CreateResponse

    return request.CreateResponse(HttpStatusCode.NoContent, user);
    

    return request.CreateResponse((HttpStatusCode)204, user);
    

    【讨论】:

    • 我正在使用 OData 控制器,它只会准备查询部分。它不会被评估。所以无论是 0 值还是大于 0,我都无法获取该值。此处获取操作代码 public IQueryable<Customers > GetCustomers() { return db.Customers ; } db.Customers 将只有选择查询,而不是 OData 中的执行结果。