Go to main content

Safe attachment URLs resolution in srcset attribute in Page Builder in Kentico Xperience

In this post, I will provide you with a quick tip on how to fix the attachment URLs resolution in srcset attribute in Page Builder in Kentico Xperience.

Problem

In Page builder, attachment URLs always get resolved in their safe version starting with /cmsctx instead of /getattachment when used in the src attribute of an img tag for example.

Regrettably, this is not the case when the attachment URL is used in the srcset attribute of a source tag inside the picture tag.

This becomes a problem when the attachment is attached to a page that is unpublished and you try to load the image in a Page builder. URLs starting with /getattachment response with 404 which is wrong.  While URLs starting with /cmsctx response with 200 which is correct.

Solution

I spoke to Kentico support and they recognized that as a bug. However, the fix would not be easy and there is a workaround that works just fine. So it won't be fixed in a hotfix. Instead, they advised me to wrap my attachment URLs in the following method in my .cshtml files:

@Url.Kentico().AuthenticateUrlRaw(attachment_url)

So, in the end, you would end up with code like this:

<picture>
    <source media="(max-width: 480px)" srcset="@Url.Kentico().AuthenticateUrlRaw(Model.SmallImageUrl)">
    <source media="(min-width: 481px)" srcset="@Url.Kentico().AuthenticateUrlRaw(Model.MediumLargeImageUrl)">
    <img src="@Model.MediumLargeImageUrl" alt="@Model.Alt">
</picture>

Further reading

all posts
  • Front-end & JavaScript

    Simple cookie bar

    EU cookie legislation requires website owners to inform visitors about the use of cookies. In this article, I will provide you with a simple solution of an informative cookie bar.

  • Front-end & JavaScript

    Simple scroll parallax

    Recently, a designer asked me to add a parallax background image on a website. I researched the web to find a suitable solution. Regrettably, I found only massive libraries that wo…

  • Kentico Xperience

    Social media share urls enhanced by Kentico macros

    Requirements of nearly every website ask us to incorporate links for sharing content on social media. There are tools out there which generates these links for us. But wh…