Hello readers, In this tutorial, I am going to show you how to play video in ASP.NET MVC. HTML5 provides us video tag to play video in our Web Applications.

Play Video in ASP.NET MVC.

Here I am going to create a simple ASP.NET MVC application to play Video.

Example:

1- Create an empty ASP.NET MVC application called PlayVideo.

Play Video

Choose an empty template and proceed.

2- Right-click on the Model folder called VideoResult and write the following code.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Hosting;
using System.Web.Mvc;

namespace PlayVideo.Models
{
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("~/Videos/Salesforce Integration with heroku.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);
}
}
}
}

Note :

Where Videos is the name of directory and Salesforce Integration with heroku.mp4 is the video file.

3- Right Click on the Controller folder and create a Controller called VideoController. Write the following code in VideoController.

using PlayVideo.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace PlayVideo.Controllers
{
public class VideoController : Controller
{
//
// GET: /Video/

public ActionResult Index()
{
return new VideoResult();
}

}
}

4- Right Click on Controller folder and create a Controller called HomeController. Write the following code.

using AjaxFileUploading.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace AjaxFileUploading.Controllers
{
public class VideoController : Controller
{
//
// GET: /Video/

public ActionResult Index()
{
return new VideoResult(); 
}

}
}

5- Right click on the Index Action method and create a Index View.

@{
ViewBag.Title = "Index";
}

<video width="320" height="240" controls autoplay="autoplay">
<source src="@Url.Action("Index","Video")" type="video/mp4">
< /video>

Output:

Play Video

Download Source Code here.

View More:

Conclusion:

I hope this is a useful tutorial for you. I would like to have your feedback, comments, and suggestions.

Thank You.

Leave a Comment