Click here to Skip to main content
15,849,032 members
Articles / Web Development / HTML5

YouTube™ API for ASP.NET

Rate me:
Please Sign up or sign in to vote.
4.97/5 (49 votes)
2 Oct 2023CPOL6 min read 228.6K   11.3K   205   23
YouTube™ API for ASP.NET, AJAX-extended (C#)
This article demonstrates how to add YouTube Video Player to ASP.NET web pages using an API written in C# and a Microsoft AJAX extension, allowing for customization of dimensions, border options, autoplay settings, and more.

Link to WebTV app based on YouTube API for ASP.NET

Fig. 1. Sample screenshot

Note: All images are included for demo purposes only. Please do not copy/redistribute.


Embedded Video Players, based either on Adobe Flash™, Microsoft Silverlight™ or pure HTML5 video technology can dramatically enhance web page aesthetics and overall user experience. This article demonstrates the coding technique for embedding the rather popular YouTube™ Video Player (which is built on the aforementioned Adobe Flash™) in ASP.NET web pages via an API written in C# and a Microsoft AJAX extension.

The project contains:

  • The default web page Default.aspx with the corresponding code-behind: both to be placed in the Application root directory (ASP.NET 2.0+).
  • Code module YouTubeScriptGenerator.cs to be placed in the App_Code directory.
  • AJAX library file (AjaxControlToolkit.dll) to be placed in the Bin directory


The Embedded Video Player is capable of streaming (playing back) the audio/video content, available from the website (Note: Subscription is not required in order to use this feature). The video item ID is encoded into a query string, looking like a random set of characters, for example: x_4CNvG1Q_M, with corresponding full address string: (in particular sample presumably pointing to the video clip titled: “Anastasia Volochkova dancing to Adiemus by Karl Jenkins).

The easiest way to embed the YouTube™ Video Player is to go to the website, select the item of interest, and then copy/paste the corresponding snippet, located in the text box marked “embed”, into your own web page, and Voila! YouTube™ site provides several customization options regarding the video player size (this includes standard settings specified as: 340x285, 445x364, 500x405, 660x525) and color palette selection. The ASP.NET YouTube™ API described in this article provides a much wider set of customization features.

Using the Code

The practical steps to embed the YouTube™ Video Player into an ASP.NET Web Page are as follows:

  1. Create or open an ASP.NET Web Site using either Microsoft Visual Studio (any edition) or the Visual Web Developer Express edition.
  2. Download the compressed (.zip) file. Extract the components into your web application directory.
  3. Set the embedded YouTube™ Video Player dimension: W/H.
  4. Customize the YouTube™ Video Player border options.
  5. Customize the YouTube™ Video Player startup settings:
    • First item to play
    • Autoplay mode
    • Starting the Video/Audio streaming at a predefined time.

Following are the code snippets corresponding to the demo ASPX web page with the associated code-behind module:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="default_aspx" %>

<!DOCTYPE html>
<html xmlns="">
<head runat="server">
    <title>YouTube ASP.NET Sample</title>
    <meta name="Description" content="YouTube Player API for ASP.NET, Demo" />
    <meta name="Keywords" content="youtube, video, player,, javascript," />
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <meta http-equiv="Author" content="Alexander Bell" />
    <meta http-equiv="Expires" content="0" />
    <meta http-equiv="Cache-control" content="no-cache" />
    <form id="form1" runat="server">
        <h3>ASP.NET Embedded Player: Demo</h3>
        <p>Initial settings: 640x480, autoplay=0</p>
        <br />
        <asp:ScriptManager ID="ScriptManager1" runat="server" />
        <asp:UpdatePanel ID="UpdatePanel1" runat="server" updatemode="Conditional" >
                <asp:DropDownList ID="cmbPlaylist" runat="server" AutoPostBack="True">
                    <asp:ListItem Value="UelDrZ1aFeY">The Beatles - Something</asp:ListItem>
                    <asp:ListItem Value="xFrGuyw1V8s">Abba - Dancing Queen</asp:ListItem>
                    <asp:ListItem Value="A_MjCqQoLLA">The Beatles - Hey Jude</asp:ListItem>
                    <asp:ListItem Value="djV11Xbc914">a-ha - Take On Me</asp:ListItem>
                    <asp:ListItem Value="1lyu1KKwC74">The Verve - Bitter Sweet Symphony</asp:ListItem>
                    <asp:ListItem Value="nVhNCTH8pDs">Pink Floyd - Learning To Fly</asp:ListItem>
                <br /><br />
                <asp:Literal ID="Literal1" runat="server"></asp:Literal>

The code-behind:

Module           :   Default.aspx.cs
Description      :   YouTube Player for ASP.NET: Demo
Developer        :   Alexander Bell
Date Created     :   09/10/2009
DISCLAIMER: This Application is provide on AS IS basis without any warranty
                 :   You can use it at your sole risk
using System;
using System.Text;
public partial class default_aspx : System.Web.UI.Page
        // player width
        private int _W = 640;

        // player height
        private int _H = 480;

        protected void Page_Load(object sender, EventArgs e)
            if (!IsPostBack)
                #region Start mode customization via Web Query String
                const string AUTO = "auto";
                const string IDX = "idx";
                int idx = 0;
                int auto = 0;

                try {
                    // autoplay param
                    string _auto = Request.QueryString[AUTO] ?? String.Empty ;
                    if (_auto != String.Empty) auto = int.Parse(_auto);

                    // item index
                    string _idx= Request.QueryString[IDX] ?? String.Empty;
                    if (_idx != String.Empty) idx = int.Parse(_idx); 

                catch { }

                // get value from the list for selected index
                cmbPlaylist.SelectedIndex = idx;

                // generate script on page load
                Literal1.Text = Get(cmbPlaylist.SelectedValue, auto, _W, _H);
                // generate script on page postback
                Literal1.Text = Get(cmbPlaylist.SelectedValue, 0, _W, _H);

    #region YouTube script to set: item, autoplay option, screen W/H
    /// <summary>
    /// YouTube player script generator (w/autoplay, W/H options)
    /// </summary>
    /// <param name="id">id</param>
    /// <param name="auto">int</param>
    /// <param name="W">int</param>
    /// <param name="H">int</param>
    /// <returns>string</returns>
    private string Get(string id, int auto, int W, int H)
        StringBuilder sb = new StringBuilder();
        sb.Append(@"<embed src='");
        // select the item to play
        // set autoplay options (indicates number of plays)
        sb.Append("' ");
        sb.Append("type='application/x-shockwave-flash' ");
        sb.Append("allowscriptaccess='never' enableJavascript ='false' ");
        sb.Append("allowfullscreen='true' ");
        // set width
        sb.Append("width='" + W.ToString() + "' ");
        // set height
        sb.Append("height='" + H.ToString() + "' ");
        string scr = sb.ToString();
        return scr;

WebTV Project

The section described powerful video streaming technology based on YouTube player embedded in ASP.NET web page. What's next? The logical extension would be adding a playlist controls and bind it to the underlying database. ASP.NET GridView control can perfectly fit the purpose: it allows creation of the templated field with advanced CSS styling [4,5] (other option would be implementing full-fledged MVC, but for such relatively simple task it seems an overkill). The possible implementation is shown below in the sample screenshot.

Backend Database

The backend database could be of any type. Its main Table should contain a mandatory VideoID field (unique key), which identifies the video item on YouTube (it's used as a web query parameter, for example: VidID=9bZkp7q19f0 corresponds to the most popular music-video of all time "Gangnam Style" by PSY). The other fields are optional, like: Title, Performer, Views, Likes, Duration, etc., so the generic video items Table creation schema may look like the following snippet:

Table 1. Video Items master table
  VidID varchar(20) NOT NULL UNIQUE,
  Title nvarchar(255) NOT NULL,
   Performer nvarchar(255),
   Duration int,
   Views long,
   Likes long,
   Dislikes long

Adding Features to WebTV

The backend database linked to the Youtube Video Player provides plenty of room for further customization/extension. The first quite obvious 'data mining' extension would be sorting the items based on their popularity. Currently (as of the year 2015) 2 YouTube 'GigaMen' identified (Justin Bieber and PSY) having 1+ billion views per a single video item, and one 'GigaLady' (Katy Perry) has been added to the said YouTube Giga-club. This astronomical popularity of music-video genre is sort of mind-boggling, indeed! With kind of bitter irony, my 4+ million CodeProject articles/tips cumulative views count put me in a category of just entry-level cat videos (so far, the most popular "Nyan Cat" video accounts for approx. 122 mega-views).

Playlist could be also customized by music genre, for example, Classical music, etc., thus creating the video channels under topical umbrella as discussed in the following sub-chapter.

Adding Channels

Possible further extension of this video-streaming technology would be creating channels by adding two more Tables to the backend DB, in addition to master table of VideoItems described above:

Table 2. Video Channels
CREATE TABLE VideoChannels
  Channel varchar(50) NOT NULL UNIQUE,
  Description nvarchar(255)
Table 3. Video Channels-Items join table
  VidID varchar(20) NOT NULL,
  Position int NOT NULL,
  Comments nvarchar(255),

where VidID and CID and Foreign Keys linking the table to the master VideoItems and Channels tables, correspondingly. Also, Unique constraint could be added to composite (VidID, CID) index in order to avoid duplicate video items appear in the same channel. Position field specifies where the item should appear in the playlist (channel), so the corresponding SQL Select statement must include the ORDER BY [Position] clause.

As mentioned above, content of the channels can be dynamically updated on time basis (daily, weekly, monthly, etc.).


This demo screenshot demonstrates the technique described above using GridView control's custom Template field.

Image 2   Image 3
Top-100 Summertime Music Videos online channel, sample screenshots


Image 4   Image 5
WebTV app w/daily scheduler, sample screenshots

Note: All images are included for demo purpose only. Please do not copy/redistribute.

In screenshot images shown above, the section to the left contains embedded YouTube player: section to the right is made of GridView control linked to the app backend database with functionality extended via JavaScript. Other controls provide additional navigation convenience (as in typical video player).

Points of Interest

Smooth transition between video items is achieved by using the Microsoft AJAX extension: notice the UpdatePanel where resides the Literal1 control containing the corresponding JavaScript.

YouTube Video Playback Customization

Other points of interest may include a video playback customization, related to the linked (not embedded) YouTube video items. This customization technique allows to:

  • Start video playback at specific position (set offset in minutes and second)
  • Specify the number of video re-plays (Loop)
  • Start the video playback in Full Screen Mode
  • Turn “Related Video” options ON/OFF
  • Set the Autoplay options
  • Set the Playback Video Quality


  • 1st August, 2014: Updated with more customization options and YouTube stats
  • 30th April, 2013: Time to switch to jQuery 2.0 (done)
  • 30th April, 2013: Made this player HTML5-compatible (key changes: <iframe class='youtube-player' type='text/html' frameborder='0' id="player"></iframe> and the rest in jQuery derived from this).
  • 20th July, 2015: The concept and implementation of WebTV Channels technical discussion has been added.


  1. YouTube™ Embedded Video Player: Extended API (C#)
  2. Click/select row in ASP.NET GridView or HTML table
  3. Nested GridView controls in ASP.NET: best practices
  4. Hyperlinked Images in ASP.NET GridView
  5. Bottle.IsNullOrEmpty(), Lounge Discussion


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Written By
United States United States
Dr. Alexander Bell (aka DrABell), a seasoned full-stack Software (Win/Web/Mobile) and Data Engineer holds PhD in Electrical and Computer Engineering, authored 37 inventions and published 100+ technical articles and developed multiple award-winning apps (App Innovation Contests AIC 2012/2013 submissions) Alexander is currently focused on Microsoft Azure Cloud and .NET 6/8 development projects.

  1. HTML5/CSS3 graphic enhancement: buttons, inputs
  2. HTML5 Tables Formatting: Alternate Rows, Color Gradients, Shadows
  3. Azure web app: Engineering Calculator VOLTMATTER
  4. Azure: NYC real-time bus tracking app
  5. Quiz Engine powered by Azure cloud
  6. 'enRoute': Real-time NY City Bus Tracking Web App
  7. Advanced CSS3 Styling of HTML5 SELECT Element
  8. Aggregate Product function extends SQL
  9. YouTube™ API for ASP.NET

Comments and Discussions

QuestionThanks for sharing youtubeapi. Got CS103 when try to compile the downloaded codes - 'cmbPlaylist' does not exist in current context Pin
Member 101314263-Oct-23 9:45
Member 101314263-Oct-23 9:45 
AnswerRe: Thanks for sharing youtubeapi. Got CS103 when try to compile the downloaded codes - 'cmbPlaylist' does not exist in current context Pin
DrABELL4-Oct-23 9:26
DrABELL4-Oct-23 9:26 
Questionupdates Pin
kiquenet.com24-May-16 11:26
professionalkiquenet.com24-May-16 11:26 
QuestionThank you Dr. for showing us the power of ASP.NET Pin
George Tourtsinakis22-Jul-15 9:03
George Tourtsinakis22-Jul-15 9:03 
AnswerRe: Thank you Dr. for showing us the power of ASP.NET Pin
DrABELL22-Jul-15 10:07
DrABELL22-Jul-15 10:07 
QuestionNice Article Pin
Santhakumar Munuswamy @ Chennai18-Jul-15 23:48
professionalSanthakumar Munuswamy @ Chennai18-Jul-15 23:48 
AnswerRe: Nice Article Pin
DrABELL19-Jul-15 2:11
DrABELL19-Jul-15 2:11 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun5-Feb-15 18:54
Humayun Kabir Mamun5-Feb-15 18:54 
GeneralRe: My vote of 5 Pin
DrABELL5-Feb-15 19:30
DrABELL5-Feb-15 19:30 
SuggestionThough I'm not test it (UAT) yet but nice poset, I think <b><big></big>Tips/Tricks</b> section you may consider so far. Pin
Md. Marufuzzaman15-Aug-14 6:22
professionalMd. Marufuzzaman15-Aug-14 6:22 
Questionhow to upload video in youtube using javascript? Pin
amit_8320-Jan-14 19:13
professionalamit_8320-Jan-14 19:13 
AnswerRe: how to upload video in youtube using javascript? Pin
DrABELL21-Jan-14 5:51
DrABELL21-Jan-14 5:51 
GeneralMy vote of 5 Pin
BadassAlien20-Aug-13 23:37
professionalBadassAlien20-Aug-13 23:37 
GeneralRe: My vote of 5 Pin
DrABELL21-Aug-13 1:36
DrABELL21-Aug-13 1:36 
GeneralMy vote of 5 Pin
John B Oliver8-May-13 13:05
John B Oliver8-May-13 13:05 
GeneralRe: My vote of 5 Pin
DrABELL8-May-13 14:14
DrABELL8-May-13 14:14 
GeneralMy vote of 5 Pin
npdev1315-Apr-13 0:03
npdev1315-Apr-13 0:03 
GeneralRe: My vote of 5 Pin
DrABELL15-Apr-13 2:15
DrABELL15-Apr-13 2:15 
GeneralNEW!! Embedded YouTube Player (WebTV project, Beta) Pin
DrABELL5-Jun-11 12:32
DrABELL5-Jun-11 12:32 
GeneralMy vote of 5 Pin
Mehedi_Hasan28-Oct-10 11:33
Mehedi_Hasan28-Oct-10 11:33 
GeneralRe: My vote of 5 Pin
DrABELL7-Dec-10 7:20
DrABELL7-Dec-10 7:20 
Generalsome query Pin
makhar22-Jul-10 18:47
makhar22-Jul-10 18:47 
GeneralRe: some query Pin
DrABELL7-Dec-10 7:32
DrABELL7-Dec-10 7:32 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.