Play Videos in ASP.NET MVC using Custom Action Filter

Posted by: Mahesh Sabnis , on 4/7/2014, in Category ASP.NET MVC
Views: 113924
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:video-download-mvc

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:

mvc-html5-play-video
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.

Absolutely Awesome Book on C# and .NET

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!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
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


Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Anish on Monday, April 14, 2014 1:22 AM
Hi Mahesh,
Can u send me link of poc project?
Actually I am looking for, how to restricting user to download video/audio.
Thanks,
Anish jain  
Comment posted by SB on Wednesday, April 23, 2014 4:31 AM
There is a difference between Action Filters and Action Results.  The author doesn't seem to understand this.
Comment posted by Nagaraju on Wednesday, April 23, 2014 8:53 AM
Nice article
Comment posted by Stephen Maher on Wednesday, April 23, 2014 9:42 AM
Very nicely done, Mahesh. Extremely lucid demonstration of the ActionResult and accompanying filter.
Comment posted by :) rta on Wednesday, April 23, 2014 2:04 PM
I think this kind of process can not be tutorial but it can be how to download file or ect. Via response, in my experience this will harmfull for program and server
Comment posted by Bozo on Wednesday, April 23, 2014 4:23 PM
What about the FILEResult?
Comment posted by tester on Thursday, April 24, 2014 11:19 PM
not working at all.
the file could be downloaded yet wouldn't play on view.
Comment posted by Mr. Tuyen on Wednesday, April 30, 2014 11:04 AM
Very nicely done, Mahesh. The author doesn't seem to understand this.

----------- End ----------
http://www.seotukhoa.vn
Comment posted by Anoop on Monday, June 16, 2014 12:24 AM
There is an error like Video format or MIME type not supported
Comment posted by Lazlo on Monday, June 30, 2014 4:34 AM
Hi, is it possible to have a mediaplayer and a user can scroll in a list of videos to select which video he/she wants to watch? Sought of a list below the player of all videos..headed by a picture. Please assist me with that if you can.
Comment posted by vikash on Saturday, July 19, 2014 6:26 PM
i am getting 404 error,can u please send the code to my mail id (dev.er.vikash@gmail.com)
Comment posted by Domonique on Monday, July 28, 2014 7:21 PM
This is not working for me at all.  I coded this word by word but I get Video format not supported in firefox which is understandable but I don't get anything in safari which is odd.  I'm using a mp4 file so safari should run that just fine.
Comment posted by lluthus on Sunday, August 3, 2014 7:00 AM
Can i add compression to output stream ? Can anyone help me ? thanks
Comment posted by iiii on Monday, August 18, 2014 2:43 AM
yuyuyuyuyuyu
Comment posted by George Lanes on Thursday, August 28, 2014 9:54 PM
Nice job. Other options!

http://www.dotnetcurry.com/showarticle.aspx?ID=924
http://weblogs.asp.net/andresv/asynchronous-streaming-in-asp-net-webapi
http://www.strathweb.com/2013/01/asynchronously-streaming-video-with-asp-net-web-api/
Comment posted by gdfg on Tuesday, September 2, 2014 12:48 AM
testing file
Comment posted by Aris on Tuesday, September 2, 2014 12:14 PM
Doesn't work with firefox.
Comment posted by Dee on Wednesday, September 3, 2014 9:16 AM
It doesn't work with Firefox.
Comment posted by Oladiti sod iq on Thursday, October 16, 2014 10:34 AM
I need a c# and asp.net code to upload and download a video
Comment posted by Anil Kushaba on Thursday, December 4, 2014 4:07 AM
This code is very easy and understandable
thanks very much
please give the code in detail
how to manually add the audio and video
Comment posted by Rick Freeman on Monday, February 2, 2015 9:39 PM
Thanks for your code.
Can you post a sample on playing multiple files from a playlist or sql DB

--
Rick
Comment posted by MAhesh Sabnis on Wednesday, February 4, 2015 12:15 AM
Hi Rick,
'I am adding the suggestions as a wishlist. I will post soon on it.
Thanks
Regards
Mahesh Sabnis
Comment posted by Alexander on Friday, April 17, 2015 6:23 AM
Thank you for the code! But I spent an hour to realize that you can not play wmv-files. By the way I propose a shorter version of the method ExecuteResult.

public override void ExecuteResult(ControllerContext context)
{
var path = HostingEnvironment.MapPath("~/Content/Mandelbrot.mp4");
context.HttpContext.Response.AddHeader("Content-Disposition", "attachment; filename=Mandelbrot.mp4");
if (File.Exists(path))
  context.HttpContext.Response.BinaryWrite(File.ReadAllBytes(path));
}
Comment posted by Nitin on Saturday, May 2, 2015 1:36 AM
Hi,

I have used this code its working well when we upload mp4 video with codec h.264 format.
but when i upload video without h.264 format its uploaded but can't see video on <video></video> tag.

Please tell me how can i load without h.264 video on chrome or IE browser.