我一直在使用WebApi进行开发,并已转移到WebApi2,其中Microsoft引入了一个IHttpActionResult似乎建议用于返回a 的新接口HttpResponseMessage.我对这个新接口的优点感到困惑.这似乎主要是公正提供SLIGHTLY更简单的方法来创建一个HttpResponseMessage.
我认为这是"为抽象而抽象"的论点.我错过了什么吗?除了节省一行代码之外,使用这个新接口可以获得什么样的真实优势?
旧方式(WebApi):
public HttpResponseMessage Delete(int id)
{
var status = _Repository.DeleteCustomer(id);
if (status)
{
return new HttpResponseMessage(HttpStatusCode.OK);
}
else
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
}
Run Code Online (Sandbox Code Playgroud)
新方式(WebApi2):
public IHttpActionResult Delete(int id)
{
var status = _Repository.DeleteCustomer(id);
if (status)
{
//return new HttpResponseMessage(HttpStatusCode.OK);
return Ok();
}
else
{
//throw new HttpResponseException(HttpStatusCode.NotFound);
return NotFound();
}
}
Run Code Online (Sandbox Code Playgroud) 我的MVC5项目解决方案中有一个WebAPI控制器.WebAPI有一个方法,它将特定文件夹中的所有文件作为Json列表返回:
[{"name":"file1.zip", "path":"c:\\"}, {...}]
从我的HomeController我想调用此方法,将Json响应转换为List<QDocument>并将此列表返回到Razor视图.此列表可能为空:[]如果文件夹中没有文件.
这是APIController:
public class DocumentsController : ApiController
{
#region Methods
/// <summary>
/// Get all files in the repository as Json.
/// </summary>
/// <returns>Json representation of QDocumentRecord.</returns>
public HttpResponseMessage GetAllRecords()
{
// All code to find the files are here and is working perfectly...
return new HttpResponseMessage()
{
Content = new StringContent(JsonConvert.SerializeObject(listOfFiles), Encoding.UTF8, "application/json")
};
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的HomeController:
public class HomeController : Controller
{
public Index()
{
// I want to …Run Code Online (Sandbox Code Playgroud) 返回类型有什么区别,例如
public class MyController : ApiController
{
public IEnumerable<MyType> Get()...
Run Code Online (Sandbox Code Playgroud)
VS
返回HttpResponseMessage:
public class MyController : ApiController
{
public HttpResponseMessage Get()...
Run Code Online (Sandbox Code Playgroud)
??
MVC是否将类型包装到HttpResponseMessage内容对象中?除非明确添加格式化程序,否则页面上的结果看起来相同.
客户有什么不同?
我想知道在我的ApiController中使用HttpResponseMessage作为返回类型有什么好处?比较直接返回键入的实体或集合.
我们试图确定一个实践,以保持我们正在进行的项目的一致性.