1

I see a lot of samples on the web for ASP.NET Web API that use Request.CreateResponse to generate responses. If you create a new Web API project in Visual Studio, the default API controllers return IEnumerable<string> or string. What's the difference in usage?

kenwarner
  • 28,650
  • 28
  • 130
  • 173
  • http://stackoverflow.com/questions/12519561/asp-net-web-api-throw-httpresponseexception-or-return-request-createerrorrespon – Vladimir Sep 02 '13 at 08:07

2 Answers2

2

Returning a HttpResponseMessage allows you to control all different aspects of the returned HTTP response directly. If you return a POCO you have to hope that the framework does what you want. And maybe it will, and maybe it won't.

Darrel Miller
  • 139,164
  • 32
  • 194
  • 243
  • ok that makes sense. Has either one evolved to be the preferred choice at this point? – kenwarner Sep 03 '13 at 00:50
  • @qntmfred I have preferred returning HTTPResponseMessage since day one. Some people prefer the idea of returning objects. Web API was intended to be a framework without opinions (other than HTTP) that allows you to choose how it will behave. – Darrel Miller Sep 03 '13 at 13:05
0

Request.CreateResponse can generate other http message, ex.404,500. If just return,the http message will be 200 OK.

In my code, if get need authorized, I will return like this:

throw new HttpResponseException(HttpStatusCode.Unauthorized);

write this,you unnecessary change the return value.

Zack Yang
  • 399
  • 2
  • 11