Prototype .NET Class Uploads Media Assets to Contentstack

This short blog post describes a prototype C# class that uploads files to the Contentstack SaaS headless CMS. I use this code to import media from a list specified in a spreadsheet. This code needs extensive refactoring and testing, but it works, I need to move on to something else, and I am publishing this as a potential reminder for myself. The code is ugly but demonstrates how to create multipart HTTP request bodies to upload files with .NET. The code is procedural and linear, which may help in following it and porting it to other platforms, but probably not in maintaining it.

The Contentstack asset upload documentation is here:

Here is the prototype code for the uploader:

AssetInfo is just a little struct for storing data about an asset.

namespace ContentstackAssetImporter
{
    using System.IO;

    public struct AssetInfo
    {
        public AssetInfo(FileInfo fileInfo, string title, string description, string folderUid = null, string tags = null)
        {
            FileInfo = fileInfo;
            Title = title;
            Description = description;
            FolderUid = folderUid;
            Tags = null;

            if (tags != null)
            {
                Tags = tags.Split("|");
            }
        }

        public FileInfo FileInfo;
        public string Title;
        public string Description;
        public string FolderUid;
        public string[] Tags;
    }
}

The only real Contentstack parts are setting the form fields asset[title], asset[description], asset[tags], asset[parent_uid], and encoding the file as asset[upload].

The mime type determination is currently hard-coded based on the filename extension. There is probably a service that maps extensions to mime types, and if there is not, there should be. Big tech companies should publicly host such generic services for free.

I am not certain that the memory stream is required to set the content length; maybe the request class would do that automatically.

Please comment if you have any suggestions and especially if you notice any defects.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: