【发布时间】:2017-07-18 04:46:17
【问题描述】:
当了解 API 时,我通常将它们编写在从 IHttpActionResult 接口返回一个方法(例如 OK())并将返回的对象作为参数放置在 OK() 方法中的位置。或者我可以只返回我从数据库中检索到的对象。
示例代码:使用 IHttpActionResult
[Route("GetAll1")]
[HttpGet]
public IHttpActionResult GetAll1()
{
List<ContactWebLink> contactWebLinks = new List<ContactWebLink>();
try
{
Manager<ContactWebLink> contactWebLinkManager = new Manager<ContactWebLink>(Unit);
contactWebLinks = contactWebLinkManager.FindAll(a => a.IsDeleted == false, null, null, null);
return Ok(contactWebLinks);
}
catch
{
return InternalServerError();
}
finally
{
contactWebLinks = null;
}
}
Vs 使用我要返回的对象的类
[Route("GetAll2")]
[HttpGet]
public List<ContactWebLink> GetAll2()
{
List<ContactWebLink> contactWebLinks = new List<ContactWebLink>();
try
{
Manager<ContactWebLink> contactWebLinkManager = new Manager<ContactWebLink>(Unit);
contactWebLinks = contactWebLinkManager.FindAll(a => a.IsDeleted == false, null, null, null);
return contactWebLinks;
}
catch
{
return null;
}
finally
{
contactWebLinks = null;
}
}
使用 Postman 测试结果,我看到了任何差异。两者都会导致 200 响应代码(当没有异常发生时)。两者都返回相同的结果(我从数据库中检索的实体)。
那么使用这两种方法有什么区别,什么时候应该使用一种而不是另一种呢?
【问题讨论】:
标签: c# json asp.net-mvc api postman