Get Salesforce content files base URL via Apex

apexcontentdocumentcontentversion

As per this salesforce help document, the content files base URL is different compare to the salesforce org domain URL.

The domain URL formats with or without enhanced domains are as follows

//with enhanced domains
Login: MyDomainName.my.salesforce.com 
VF page: MyDomainName--PackageName.vf.force.com 
Content(files): MyDomainName.file.force.com

//without enhanced domains
Login: MyDomainName.my.salesforce.com 
VF page: MyDomainName--PackageName.visualforce.com 
Content(files): MyDomainName--c.documentforce.com

In the VF page context, we can do mapping of the VF page URL i.e Url.getSalesforceBaseUrl() and Content Page URL, and get the content URL. But in the case of Webservice context URL.getOrgDomainUrl() or Url.getSalesforceBaseUrl() is the same with or without enhanced domains. So we cant keep mapping and get content files URL via apex dynamically in apex.

How to find out content files URL using Url.getSalesforceBaseUrl() OR URL.getOrgDomainUrl() through apex?

Best Answer

You can use the DomainCreator class for this. It will return the correct URL no matter if the enhanced domains were enabled or not:

DomainCreator.getContentHostname()