November Happy Hour will be moved to Thursday December 5th.

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

Vote:
 

Hello,

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.

Thanks,

Deepa

#296997
Feb 22, 2023 7:26
Vote:
 

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

#296998
Feb 22, 2023 9:11
Vote:
 

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;
    }
#296999
Feb 22, 2023 9:13
Vote:
 

Thank you both for all the help.

#297000
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.