相关疑难解决方法(0)

我为什么要使用IHttpActionResult而不是HttpResponseMessage?

我一直在使用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)

c# httpresponse asp.net-web-api

312
推荐指数
6
解决办法
19万
查看次数

标签 统计

asp.net-web-api ×1

c# ×1

httpresponse ×1