IHttpActionResult vs HttpResponseMessage

Video ready, click here to close ×


Text version of the video
http://csharp-video-tutorials.blogspot.com/2017/02/ihttpactionresult-vs-httpresponsemessage.html

Slides
http://csharp-video-tutorials.blogspot.com/2017/02/ihttpactionresult-vs-httpresponsemessage_22.html

All ASP .NET Web API Text Articles and Slides
http://csharp-video-tutorials.blogspot.com/2016/09/aspnet-web-api-tutorial-for-beginners.html

All ASP .NET Web API Videos

Video ready, click here to close ×

All Dot Net and SQL Server Tutorials in English
https://www.youtube.com/user/kudvenkat/playlists?view=1&sort=dd

All Dot Net and SQL Server Tutorials in Arabic
https://www.youtube.com/c/KudvenkatArabic/playlists

In Web API 1, we have HttpResponseMessage type that a controller action method returns. A new type called “IHttpActionResult” is introduced in Web API 2 that can be returned from a controller action method. Instead of returning HttpResponseMessage from a controller action, we can now return IHttpActionResult. There are 2 main advantages of using the IHttpActionResult interface.

1. The code is cleaner and easier to read
2. Unit testing controller action methods is much simpler. We will discuss, how easy it is to unit test a method that returns IHttpActionResult instead of HttpResponseMessagein a later video.

Consider the following StudentsController. Notice both the Get() methods return HttpResponseMessage. To create the HttpResponseMessage, we either use CreateResponse() or CreateErrorResponse() methods of the Request object.

public class StudentsController : ApiController
{
static List[Student] students = new List[Student]()
{
new Student() { Id = 1, Name = “Tom” },
new Student() { Id = 2, Name = “Sam” },
new Student() { Id = 3, Name = “John” }
};

public HttpResponseMessage Get()
{
return Request.CreateResponse(students);
}

public HttpResponseMessage Get(int id)
{
var student = students.FirstOrDefault(s =] s.Id…

source

4 comments

Leave a Reply

Your email address will not be published. Required fields are marked *