Display Instagram user feed on your website with C# and ASP.NET MVC4

30 July 2013

We recently got a request to add a custom Instagram image feed to a travel blog that we'd developed, this is and how we did it and what we found out along the way.

To access a specific user's feed through the Instagram API you must first register a new Instagram OAuth Client at http://instagram.com/developer/clients/register which your website will use to access the API.

Next you need to grant permission to the new application to access the Instagram API on your behalf, the easiest way to do this is by going to the Instagram authorization URL below, just replace the querystring parameters CLIENT-ID and REDIRECT-URI with the values from your client application:

https://instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=token

You'll be prompted to give access to the application, then you'll be redirected back to the REDIRECT-URI with an access token appended to the end in the url fragment, ie:

http://REDIRECT-URI#access_token=ACCESS-TOKEN

Copy the value of the access token, it's what you'll be using in your C# code to authenticate to the Instagram API.

There are a couple of NuGet packages you can use to access the Instagram API, I went with the Skybrud.Social package because it looked easy to use, and it was, I was able to get the 9 latest images from a user feed with the following C# code in my MVC4 controller:

// instagram feed
var instagram = InstagramService.CreateFromAccessToken(ACCESS-TOKEN);
var media = instagram.Endpoints.Users.GetMedia(USER-ID, 9);
return View(media);

And displayed it with the following code in my MVC4 view (although obviously you can use any markup you like):

<ul class="instagram">
    @foreach (var image in Model.Images)
    { 
        <li>
            <div class="image_frame">
                <a href="/instagram-@image.Id/@image.CaptionText.Slugify()" title="@image.CaptionText">
                    <img src="@image.Thumbnail" />
                </a>
            </div>
        </li>
    }
</ul>