【发布时间】:2012-09-04 22:55:44
【问题描述】:
对于来自操作方法的返回类型,Web API 中的一般做法是什么?
像这样返回 CLR 对象:
public IEnumerable<ContactModel> Get()
{
return _contactService.GetAllForUser();
}
或者将您的对象包装在HttpResponseMessage:
public HttpResponseMessage Get()
{
IEnumerable<ContactModel> contacts = _contactService.GetAllForUser();
return Request.CreateResponse((HttpStatusCode) 200, contacts);
}
我更喜欢使用我自己的 CLR 对象作为返回类型,因为它显然会产生更简洁的方法,因为您不必每次都实例化 HttpResponseMessage。
【问题讨论】:
-
AFAIK,如果您返回 CRL 类型,如果出现异常,异常消息会传播到客户端,这不是一个好习惯。
-
显然不是——但看看@Claudio 的回答,他建议您可以使用 HttpResponseException 捕获异常并向客户端返回适当的响应
标签: c# .net asp.net-web-api