Play Videos in ASP.NET MVC using Custom Action Filter

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

Give a +1 to this article if you think it was well written. Thanks!
Recommended Articles


Page copy protected against web site content infringement by Copyscape


User Feedback
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

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel