Content Hub: Get public link for asset from Web SDK Client

Today our topic is getting the public link(s) for an asset in the Content Hub via Web SDK Client. Therefore we first need the configuration and client. Keep in mind, that the user you use must be a superuser.

// Your Sitecore Content Hub endpoint to connect to
Uri endpoint = new Uri("https://yourcontenthuburl");

// Enter your credentials here         
OAuthPasswordGrant oauth = new OAuthPasswordGrant         
{             
  ClientId = "yourclientid",             
  ClientSecret = "yourclientsecret",             
  UserName = "yoursuperusername",             
  Password = "youruserpassword"         };         

// Create the Web SDK client         
IWebMClient client = MClientFactory.CreateMClient(endpoint, oauth);         client.TestConnectionAsync().Wait();

Now we query our specific asset just by id this time.

// our test-id : 29578
var testQueryId = Query.CreateQuery(
entities =>
 from e in entities
 where e.Id == assetId
 select e.LoadConfiguration(QueryLoadConfiguration.Full));

IEntity testResult = client.Querying.SingleAsync(testQueryId).Result;         

Now we get the “assettopubliclink” relation for retrieving the public links.

IParentToManyChildrenRelation testRelation = testResult.GetRelation<IParentToManyChildrenRelation>(PublicLink.AssetToPublicLink);         

Last we can find out the public links.

List<string> links = new List<string>();         

foreach (long publicLinkId in testRelation.Children)         
{             
  Query q = Query.CreateQuery(entities =>                
    from e in entities                
    where e.Id == publicLinkId                
    select e.LoadConfiguration(QueryLoadConfiguration.Default)
.WithProperties(PropertyLoadOption.All));             

IEntity entity = client.Querying.SingleAsync(q).Result;           
var relativeUrl = entity.GetPropertyValue<string>("RelativeUrl");             var versionHash = entity.GetPropertyValue<string>("VersionHash");             var publicLink = $"api/public/content/{relativeUrl}?v={versionHash}";             links.Add(publicLink);         
}

Now we have a list of public links for the specific asset and can work with this.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.