SaaS CMS has officially launched! Learn more now.

EPiServer CMS 12 website UrlHelper.ContentUrl(contentreference) error on reload of the page



Below code works just fine to fetch siteasset or globalasset path on first load for the contentreference item passed as an argument. 

 public static string GetFriendlyLink(ContentReference contentReference)
            var friendlyUrl = string.Empty;
            if (contentReference != null)
                var urlHelper = ServiceLocator.Current.GetInstance<IUrlHelper>();
                friendlyUrl = urlHelper.ContentUrl(contentReference);

            return friendlyUrl;

But on reload gives Value can't be Null exception for argument. 

Value cannot be null. (Parameter 'provider')
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)

Adding UrlResolver works always. Can this be switched to UrlResolver instead of UrlHelper?

Please help on this.



Feb 22, 2023 7:26

You should be using IUrlResolver. I don't even recognize IUrlHelper, it's not part of our public APIs

Feb 22, 2023 9:11

Hi Deepa,

If you take a look inside the method ContentUrl of UrlHelper, it uses the IUrlResolver internally.
I would advise to cut the middle man and use the IUrlResolver :) 

    /// <summary>
    /// Resolves an URL using routing for a specific <see cref="T:EPiServer.Core.ContentReference" />
    /// </summary>
    /// <param name="urlHelper">The URL helper instance that this method extends</param>
    /// <param name="contentLink">The content reference to resolve</param>
    /// <returns>The URL or an empty string</returns>
    public static string ContentUrl(this IUrlHelper urlHelper, ContentReference contentLink)
      UrlResolver requiredService = urlHelper.ActionContext.HttpContext.RequestServices.GetRequiredService<UrlResolver>();
      if (!ContentReference.IsNullOrEmpty(contentLink))
        string url = requiredService.GetUrl(contentLink);
        if (!string.IsNullOrEmpty(url))
          return UrlEncoder.Encode(url);
      return string.Empty;
Feb 22, 2023 9:13

Thank you both for all the help.

Feb 22, 2023 9:29
This topic was created over six months ago and has been resolved. If you have a similar question, please create a new topic and refer to this one.
* You are NOT allowed to include any hyperlinks in the post because your account hasn't associated to your company. User profile should be updated.