Anchor for Header

React and .NET CORE SPA getting og:image

Anchor for Text


Recently I was creating a really epic Reactjs and .NET Core site that actually hosts many clients and I got really stuck with the og:image tag

The key issue is the Facebook does not compile javascript or any other scripts for your site, so it reads the index.html public page 'as is'.

This is only problematic when you are trying to host multiple dynamic sites in your SPA. If you only need an image for one site, you can just use a url to an image hard-coded.

I was unable to find a way to dynamically create an index.html page either. So I was really stuck and weeks later I was able to come up with a way to add a default og:image for each of my sites.

Basically all you have to do is this in your index.html page and it will then dynamically fetch the results:


 <meta property="og:image" content="/api/Website/GetSocialMediaBanner" />


So this tells facebook to go fetch the content from the sites API, rather than a hard coded link to a file.


In your .NET website Controller (your controller might not be called Website so adjust the above link to suite your site) you will need to get the sites og:image and return it.

This provides an elegant solution to a default OG:Image for an entire site.




Anchor for Text

Here is an example of the .NET core code


Anchor for DisplayCode
/// <summary>         
/// Get the og:image for this site          
/// If the actual page has a Teaser image, this is returned instead         
/// </summary>         
/// <returns></returns>                 
[HttpGet("[action]")]         
public FileResult GetSocialMediaBanner()         {
            
//Write your own logic to get this sites default og:image here
string Url = 'https://membersblob.blob.core.windows.net/members/DEV/media/Experimental-Hero1.png';


            if (Url != "")             
                 var webClient = new WebClient();
                 byte[] imageBytes = webClient.DownloadData(Url);

                if (imageBytes != null)
                 { string filename = Path.GetFileName(Url);
                    Stream stream = new MemoryStream(imageBytes);
                     return   new FileStreamResult(stream, "image/" + Path.GetExtension(Url)) { FileDownloadName = filename };
                   }
return null;
       }
Anchor for Text

In my case, the function to get the value out of the database is unique for each site, so it gets that sites default OG Image. Your services would know the differences for each site too, if at minimum by the Request.Url that the user calls this function on.



log in to comment

Anchor for PageNextPrevious
popupimage

EZ Proxy SHA256 Example for OCLC

A working example of a SHA256 EZ Proxy authentication model

Read More