Kentico Xperience 13 documentation and ASP.NET Core

Most documentation about running Xperience applications under ASP.NET Core can be found in a dedicated section: Developing Xperience applications using ASP.NET Core. The rest of the documentation still applies, but some code samples and scenarios might need slight modifications for Core projects.

All major differences between the MVC 5 and Core platforms are summarized in Migrating to ASP.NET Core.

×

Displaying content from media libraries

Media libraries serve as a data storage for your application. They can store different types of audio, video, image, and document files. For a complete list of the file types supported by default, see Supported file types in Media libraries.

This page covers how you can:

Retrieving media library files

The following example demonstrates how to retrieve files from Xperience media libraries in MVC applications. The example uses a media library with the code name SampleMediaLibrary. For this example to function, substitute the code name with any media library from your site.

  1. Open your live site project in Visual Studio.
  2. Create a view model class representing media files. Define properties for storing the media file values that you wish to use in your views.
  3. Create a new controller class or edit an existing one.
  4. Implement a GET action method to retrieve media files. This example retrieves .jpg files from the SampleMediaLibrary media library.

  5. Use the view model to pass media file data to your views.

Required using statements
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
 
using CMS.Base;
using CMS.MediaLibrary;
 
using Kentico.Content.Web.Mvc;
Retrieving media files in a controller action
        private readonly IMediaFileUrlRetriever mediaFileUrlRetriever;
        private readonly IMediaLibraryInfoProvider mediaLibraryInfoProvider;
        private readonly IMediaFileInfoProvider mediaFileInfoProvider;
        private readonly ISiteService siteService;
 
        // Initializes instances of required services using dependency injection
        public MediaLibraryController(IMediaFileUrlRetriever mediaFileUrlRetriever,
                                      IMediaLibraryInfoProvider mediaLibraryInfoProvider,
                                      IMediaFileInfoProvider mediaFileInfoProvider,
                                      ISiteService siteService)
        {
            this.mediaFileUrlRetriever = mediaFileUrlRetriever;
            this.mediaLibraryInfoProvider = mediaLibraryInfoProvider;
            this.mediaFileInfoProvider = mediaFileInfoProvider;
            this.siteService = siteService;
        }
 
 
        /// <summary>
        /// Retrieves media files with the .jpg extension from the 'SampleMediaLibrary'.
        /// </summary>
        public ActionResult ShowMediaFiles()
        {
            // Gets an instance of the 'SampleMediaLibrary' media library for the current site
            MediaLibraryInfo mediaLibrary = mediaLibraryInfoProvider.Get("SampleMediaLibrary", siteService.CurrentSite.SiteID);
            
            // Gets a collection of media files with the .jpg extension from the media library
            IEnumerable<MediaFileInfo> mediaLibraryFiles = mediaFileInfoProvider.Get()
                                        .WhereEquals("FileLibraryID", mediaLibrary.LibraryID)
                                        .WhereEquals("FileExtension", ".jpg");
                        
            // Prepares a collection of view models containing required data of the media files
            IEnumerable<MediaFileViewModel> model = mediaLibraryFiles.Select(
                    mediaFile => {
                        IMediaFileUrl fileUrl = mediaFileUrlRetriever.Retrieve(mediaFile);
                        return new MediaFileViewModel
                        {
                            FileTitle = mediaFile.FileTitle,
                            // Gets the relative path to the media file
                            RelativeUrl = fileUrl.RelativePath
                        };
                    }
            );
 
            // Passes the model to the view
            return View(model);
        }

Getting media file URLs

To resolve the URLs of retrieved media library files (MediaFileInfo objects), use the IMediaFileUrlRetriever service from the Kentico.Content.Web.Mvc namespace. The service exposes a Retrieve method that takes a MediaFileInfo object as its parameter and returns an IMediaFileUrl instance with the following properties:

  • string RelativePath – the application relative (starting with '~/') permanent path to the file. For example: ~/getmedia/0140bccc-9d47-41ea-94a9-ca5d35b2964c/sample_image.jpg. This format ensures that the image remains accessible if the file is renamed or moved to a different media library or directory on the file system.
  • string DirectPath – the direct path to the media file on the filesystem. For example: ~/MediaLibraryFolder/sample_image.jpgThese URLs change whenever the file is renamed or moved to a different media library (directory on the filesystem). 
  • NameValueCollection QueryStringParameters – a collection of query string parameters appended to the URL. See Parameterizing retrieved URLs
  • bool IsImage – a boolean flag stating whether the URL leads to an image file.

Parameterizing retrieved URLs

You can further parameterize the retrieved file URLs via extension methods on the IMediaFileUrl object. The extension methods add query string parameters that change the URL behavior and allow you to customize the format of the files. The following extensions are available:

  • WithOptions – used to provide additional configuration for the URL via a FileUrlOptions object. Using the object, you can specify:

    • Content disposition – configured via the AttachmentContentDisposition boolean property. Determines whether the file gets displayed inline (false) or requires some form of user action to download (true).

      using Kentico.Content.Web.Mvc
       
      ...
       
      // Forces a download of the media file when its URL is accessed
      // The mediaFileUrl variable is an IMediaFileUrl object obtained via IMediaFileUrlRetriever
      IFileUrl mediaFileUrlWithOptions = mediaFileUrl.WithOptions(new FileUrlOptions { AttachmentContentDisposition = true});
  • WithSizeConstraint – used to resize image media files. You can resize image files via the SizeConstraint parameter of the method. Note, however, that this parameterization never upscales the image. The following image size constraints are available:
    • SizeConstraint.Empty – leaves the image unchanged.

    • SizeConstraint.Height(100) – resizes the image to the specified height (maintains aspect ratio).
    • SizeConstraint.Width(100) – resizes the image to the specified width (maintains aspect ratio).
    • SizeConstraint.MaxWidthOrHeight(100) – resizes the image so that its width and height do not exceed the specified value (maintains aspect ratio).
    • SizeConstraint.Size(100, 120) – resizes the image to the specified width and height. Does not maintain aspect ratio.

      It is not possible to resize image files via the SizeConstraint parameter when using direct URLs. This is caused by the fact that files accessed from direct URLs are handled directly by IIS.

Displaying media library files

To display media library files on your site, create views that work with the generated media file URLs. To convert relative URLs to their application absolute format, use methods from the framework's UrlHelper class, such as Url.Content:

Media file view example
@model IEnumerable<MediaFileViewModel>
 
 
<h2>Media library file listing</h2>
 
@foreach (MediaFileViewModel mediaFile in Model)
{
    @* Gets an application absolute URL for the media file *@
    string url = Url.Content(mediaFile.RelativeUrl);
 
    <img src="@url" alt="@mediaFile.FileTitle" />
}

Media libraries on external storage

To store media library files in an external storage (cloud-based file system), you need to:

  1. Configure your live site application to use the given external storage provider for the media library folder.
  2. Always link to content in an external storage using Permanent URLs.

Was this page helpful?