2016年6月12日 星期日

Why IHttpActionResult

Action Results in Web API 2 The IHttpActionResult interface was introducted in Web API 2. Essentially, it defines an HttpResponseMessage factory. Here are some advantages of using the IHttpActionResult interface:
  • Simplifies unit testing your controllers.
  • Moves common logic for creating HTTP responses into separate classes.
  • Makes the intent of the controller action clearer, by hiding the low-level details of constructing the response.
other advantages:

  • Respecting to single responsibility principle: cause action methods have the responsibility of serving the HTTP requests and should not involve in creating the HTTP response messages.
  • Useful implementations already defined in the System.Web.Http.Results namely: 
    • Ok
    • NotFound
    • Exception
    • Unauthorized
    • BadRequest
    • Conflict
    • Redirect
    • InvalidModelState
    • 完整列表
  • Uses Async and Await by default.
  • Easy to create own ActionResult just by implementing ExecuteAsync method.
  • you can use ResponseMessageResult ResponseMessage(HttpResponseMessage response) to convert HttpResponseMessage to IHttpActionResult.