Play Videos in ASP.NET MVC using Custom Action Filter
Posted by: Mahesh Sabnis ,
on 4/7/2014,
in
Category ASP.NET MVC
Abstract: The ASP.NET MVC framework can be extended using the Custom Action Filter to play videos. This article shows how to do it in HTML5 and ASP.NET MVC .
Although the built-in result classes are sufficient for most application scenarios in ASP.NET MVC, it’s worth noting that one of the most important features in ASP.NET MVC is that a developer can extend this framework for occasions where your application requires something special. For eg: the Custom View Engine, Custom Controller Factory, Custom Action Result, Custom Action Filter can be used to extend ASP.NET MVC for your application requirements. This makes MVC as the most adaptive technology for web application development today.
Playing Video files in ASP.NET MVC
One such requirement in a web application could be that it allows binary contents e.g. images, videos, pdf etc. to be downloaded. ASP.NET MVC facilitates this requirement via the ActionResult abstract class. The derived classes from the ActionResult such as the FileContentResult and FileStreamResult classes are useful to perform binary file download operations. However now consider the scenario that you as a developer want to restrict the Action method to download only the video file and sometimes instead of downloading it physically on the disk, just play it directly. Now that’s a special requirement, so how do we implement it in MVC? Enter the Custom Action Result which gets the job done!
Note: The example is just a demo to show the implementation of Custom ActionResult feature in MVC. Downloading Video or playing Video directly in a browser can be possible using various other methods in Web Applications.
Step 1: Open VS 2012/2013 and create an ASP.NET MVC Empty application. Name it as ‘MVC_CustomActionResult’. In this project, add a new folder and name it as ‘VideoFile’. In this folder, add Video files as per your choice. (I have used the .mp4 format)
Step 2: In the project, add a new folder name it as ‘CustomResult’. In this folder add a new class file and name it as ‘VideoResult.cs’. Add the following code in it:
using System.IO;
using System.Web.Hosting;
using System.Web.Mvc;
namespace MVC_CustomActionResult.CustomResult
{
public class VideoResult : ActionResult
{
/// <summary>
/// The below method will respond with the Video file
/// </summary>
/// <param name="context"></param>
public override void ExecuteResult(ControllerContext context)
{
//The File Path
var videoFilePath = HostingEnvironment.MapPath("~/VideoFile/Win8.mp4");
//The header information
context.HttpContext.Response.AddHeader("Content-Disposition", "attachment; filename=Win8.mp4");
var file = new FileInfo(videoFilePath);
//Check the file exist, it will be written into the response
if (file.Exists)
{
var stream = file.OpenRead();
var bytesinfile = new byte[stream.Length];
stream.Read(bytesinfile, 0, (int)file.Length);
context.HttpContext.Response.BinaryWrite(bytesinfile);
}
}
}
}
The ExecuteResult method implementation above looks for the Video file. If it is found, then set the response by writing the file into the response.
Step 3: In the application, add a new MVC Empty Controller, name it as VideoController and implement the code as below:
using MVC_CustomActionResult.CustomResult;
using System.Web.Mvc;
namespace MVC_CustomActionResult.Controllers
{
public class VideoController : Controller
{
//
// GET: /Video/
public ActionResult Index()
{
return new VideoResult();
}
}
}
The Index method now returns the VideoResult; the custom action result implemented in the previous step.
Step 4: Run the application and navigate to the, Video/Index URL and the download experience will be similar to the following:
Step 5: In the project, add a new MVC Empty controller with the name SampleController, and add an index method in it as shown below:
public class SampleController : Controller
{
//
// GET: /Sample/
public ActionResult Index()
{
return View();
}
}
Step 6: Add a new View from the above action method, and add the following HTML 5 Video tag in it:
<video width="320" height="240" controls autoplay="autoplay">
<source src="@Url.Action("Index","Video")" type="video/mp4">
< /video>
The video tag shown above is provided in HTML 5. The src property is set to the Index method in the Video controller which we have implemented in Step 3.
Step 7: Run the application in a Browser (I have used Chrome), and the result will be as below:
That’s it. So now you can have your ASP.NET MVC application ready for playing various videos in the browser.
This is a handy page that shows which browser supports HTML5 Video and in which video format.
Conclusion: In ASP.NET MVC, using its extensibility feature, a developer can implement domain based requirements to provide the best end-user experiences. Custom ActionResult is one of the mechanism using which developer can think of defining some restrictions on the responses delivered to the Browser.
This article has been editorially reviewed by Suprotim Agarwal.
C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.
We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).
Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.
Click here to Explore the Table of Contents or Download Sample Chapters!
Was this article worth reading? Share it with fellow developers too. Thanks!
Mahesh Sabnis is a DotNetCurry author and a Microsoft MVP having over two decades of experience in IT education and development. He is a Microsoft Certified Trainer (MCT) since 2005 and has conducted various Corporate Training programs for .NET Technologies (all versions), and Front-end technologies like Angular and React. Follow him on twitter @
maheshdotnet or connect with him on
LinkedIn