Back to Blog
Jan 24, 2023

Integrate streaming video into your .NET application

Written by Zack Schwartz


Introduction

Creating a comprehensive streaming video website requires a thorough understanding of the various components that make up the user experience. From the list view displaying thumbnails, titles, and creator information, to the detailed view featuring the video itself, a title, and a longer description, there are many elements to consider. While it may be tempting to take a simple approach, such as uploading MP4 videos and embedding them using the <video> HTML tag, this method has its limitations and is not the most efficient approach. A more comprehensive approach is necessary to fully realize the potential of your streaming video website.

Limitations of strictly using .mp4s

When using the <video> tag to display .mp4 files on your website, the following limitations should be taken into consideration:

  • High bandwidth costs as visitors will be downloading the entire video on each page visit.
  • Limited compatibility as not all browsers or devices may be able to play .mp4 files.
  • Reduced user experience as it may not be possible to offer features such as video skipping or hover-over thumbnails.
  • Limited video performance metrics, as it may not be possible to track watch time, skip aheads, and other data.

This is not an exhaustive list of limitations, but should give you a good idea of what to watch out for. In reality, I would only strongly consider using .mp4 files if you have a small videos and a low traffic website.

Streaming video providers

The COVID-19 pandemic has greatly impacted the development of streaming video technology. The shift towards virtual meetings and events, such as Zoom and GoToMeeting, as well as the increased need for recorded content to be stored on websites and Learning Management Systems, has led to a significant advancement in the technology. Many organizations, particularly those in the form of association conferences, were forced to cancel in-person meetings and move to virtual conferences, leading to an increase in demand for streaming video providers. One such provider, Mux.com, which was already established before the pandemic, saw significant growth during this time. Additionally, new players entering the market, such as Cloudflare Stream, have also led to a decrease in prices for streaming video services.

Integrate Mux.com Streaming Video into your .NET application

Getting started with Mux.com is quite straight forward. Create an account on their website and they allow you to upload videos truncated to 10 seconds and a watermark so that you can begin testing. You then need to create a set of API credentials which will provide you an API Token ID and API Secret Key. You should store these securely in your .NET application's environment variables or Vault.

The following is a code snippet from the Youtube video that accompanies this blog post. This code is a basic implementation of calling the Mux.com API to create a video asset and then retrieve a Playback ID. It makes use of the RestSharp library to make the API call.

using Microsoft.Extensions.Configuration;
using Raytha.Application.Common.Interfaces;
using RestSharp;
using RestSharp.Authenticators;
using System.Text.Json;

namespace Raytha.Infrastructure.Services;

public class Mux : IStreamingVideoProvider
{
    private const string MUX_ENDPOINT = "https://api.mux.com/";
    private string _muxTokenId;
    private string _muxSecretKey;

    public Mux(IConfiguration configuration)
    {
        _muxTokenId = configuration["MUX_TOKEN_ID"];
        _muxSecretKey = configuration["MUX_SECRET_KEY"];
    }

    public async Task<string> CreateAssetAsync(string url)
    {
        //take in a URL to the video asset that is accessible over the internet
        string muxPayload = JsonSerializer.Serialize(new MuxPayload { input = url });

        //post the video the API using the API credentials
        var client = new RestClient(MUX_ENDPOINT);
        client.Authenticator = new HttpBasicAuthenticator(_muxTokenId, _muxSecretKey);
        var request = new RestRequest("video/v1/assets", Method.Post);
        request.RequestFormat = DataFormat.Json;
        request.AddBody(muxPayload);
        var response = await client.ExecuteAsync(request);

        //process the response, mapping the JSON back to static models and parse out the playback ID
        if (response.IsSuccessful)
        {
            var muxVideoResponse = JsonSerializer.Deserialize<MuxResponseRoot>(response.Content);
            return muxVideoResponse.data.playback_ids[0].id;
        }
        else
        {
            return $"Error: {response.ErrorMessage}";
        }
    }
}

internal class MuxPayload
{
    public string input { get; set; }
    public List<string> playback_policy { get; set; } = new List<string> { "public" };
}

internal class MuxResponseData
{
    public string status { get; set; }
    public List<MuxResponsePlayBackId> playback_ids { get; set; }
    public string mp4_support { get; set; }
    public string master_access { get; set; }
    public string id { get; set; }
    public string created_at { get; set; }
}

internal class MuxResponsePlayBackId
{
    public string policy { get; set; }
    public string id { get; set; }
}

internal class MuxResponseRoot
{
    public MuxResponseData data { get; set; }
}


Once you've posted and saved the Playback ID from the Mux API, you can make the video available to your website visitors by using the Mux Video Player as shown below.

Take note of the playback-id's value is a typical Raytha Liquid Syntax variable where we assume you have stored the playback ID inside a custom content model whose developer name is called mux_playback_id.

<script src="https://unpkg.com/@mux/mux-player"></script>
<mux-player
  stream-type="on-demand"
  playback-id="{{ Target.PublishedContent.mux_playback_id.Value }}"
  metadata-video-title="Placeholder (optional)"
  metadata-viewer-user-id="Placeholder (optional)"
  primary-color="#FFFFFF"
  secondary-color="#000000">
</mux-player>

There you go! Not much more to it than that.

picture of the author
Zack Schwartz @apexdodge

ENTREPRENEUR & SOFTWARE ENGINEER, AUSTIN, TX
I enjoy tackling a wide array of business challenges ranging from front line product support and operations to sales and marketing efforts. My core expertise is in software development building enterprise level web applications.


Subscribe to the Raytha newsletter