是不是总能在Web Api中返回HttpResponseMessage?

cho*_*bo2 17 asp.net-web-api

我一直在想这一段时间,总是HttpResponseMessage使用asp.net mvc web api 返回web 更好吗?

当我加载默认的webapi项目时,我发现它们不在样本控制器中使用它

 // GET api/values
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/values/5
        public string Get(int id)
        {
            return "value";
        }
Run Code Online (Sandbox Code Playgroud)

我认为HttpResponseMessage包装所有内容并使其成为一个很好的Http请求.如果这是正确的,不仅仅使用它的好处是什么?

Dar*_*ler 18

我总是返回HttpResponseMessage.Web API的重点是能够公开HTTP API.假装您正在返回一个对象,然后依靠框架管道将对象转换为HTTPResponseMessage,这只是模糊了IMO的意图.

我相信,如果您自己支付创建HttpResponseMessage的额外费用,您将更好地了解Web API的实际工作方式.您将遇到更少的问题,因为您更有可能避免Web API执行您不期望的事情.您将更有可能利用HTTP功能,因为标题就在那里供您访问.

  • @PaulDevenney如果你抛出一个包含HttpResponseMessage的HttpResponseException,你仍然可以包含一个"ReasonPhrase",如下所示:http://www.asp.net/web-api/overview/web-api-routing-and-actions/exception-处理 (3认同)