RUVIDEO
Поделитесь видео 🙏

IHttpActionResult vs HttpResponseMessage

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

Healthy diet is very important both for the body and mind. If you like Aarvi Kitchen recipes, please support by sharing, subscribing and liking our YouTube channel. Hope you can help.
https://www.youtube.com/channel/UC7sEwIXM_YfAMyonQCrGfWA/?sub_confirmation=1

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
https://www.youtube.com/playlist?list=PL6n9fhu94yhW7yoUOGNOfHurUE6bpOO2b

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 == id);
if(student == null)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Student not found");
}

return Request.CreateResponse(student);
}
}

In the following example, we have replaced both instances of HttpResponseMessage with IHttpActionResult. To return status code 200, we used Ok() helper method and to return status code 404, we used NotFound() method. To the Ok() method we have passed the type we want to return from the action method. Also notice, the code is now much cleaner and simpler to read.

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 IHttpActionResult Get()
{
return Ok(students);
}

public IHttpActionResult Get(int id)
{
var student = students.FirstOrDefault(s =] s.Id == id);
if(student == null)
{
return Content(HttpStatusCode.NotFound, "Student not found");
// return NotFound();
}

return Ok(student);
}
}

In addition to Ok() and NotFound() helper methods, we have the following methods that we can use depending on what we want to return from our controller action method. All these methods return a type, that implements IHttpActionResult interface.
BadRequest()
Conflict()
Created()
InternalServerError()
Redirect()
Unauthorized()

Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «IHttpActionResult vs HttpResponseMessage», вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.

Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.

Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!

Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.