【发布时间】:2012-10-02 16:51:28
【问题描述】:
我正在使用 Asp.Net Web Api 的发布版本创建一个 API。如果没有找到结果,我正在尝试传回正确的响应代码 (404)。
首次获取版本(抛出多个枚举错误):
public IEnumerable<MyObjectType> Get(int id, string format)
{
var db = new DbEntities();
var result = db.pr_ApiSelectMyObjectType(store, id, format).AsEnumerable();
if (result.Any())
{
return result;
}
var response = new HttpResponseMessage(HttpStatusCode.NotFound)
{ Content = new StringContent("Unable to find any results") };
throw new HttpResponseException(response);
}
第二次获取版本(结果永远不会为空,所以总是返回 200):
public IEnumerable<MyObject> Get(int id, string format)
{
var db = new DbEntities();
var result = db.pr_ApiSelectMyObjectType(store, id, format);
if (result == null)
{
var response = new HttpResponseMessage(HttpStatusCode.NoContent)
{ Content = new StringContent("Unable to find any results") };
throw new HttpResponseException(response);
}
return result.AsEnumerable();
}
如果没有找到结果,我该如何回传 404?我知道我可以使用一个列表,但我有一个自定义 csv 媒体类型格式化程序,它只适用于 IEnumerable 类型,所以我更愿意坚持使用它。
【问题讨论】:
标签: c# asp.net asp.net-web-api