Skip to content

Instantly share code, notes, and snippets.

@jfversluis
Created July 27, 2018 08:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jfversluis/188fc3d591e7c7a9e94753158ca1cf93 to your computer and use it in GitHub Desktop.
Save jfversluis/188fc3d591e7c7a9e94753158ca1cf93 to your computer and use it in GitHub Desktop.
Getting the URL preview from Azure
public static MetaInformation GetUrlPreview(string url, string apikey)
{
try
{
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", apikey);
using (Stream s = httpClient.GetStreamAsync($"https://api.labs.cognitive.microsoft.com/urlpreview/v7.0/search?q={url}").Result)
using (StreamReader sr = new StreamReader(s))
using (JsonReader reader = new JsonTextReader(sr))
{
var serializer = new JsonSerializer();
var result = serializer.Deserialize<UrlPreviewResult>(reader);
return new MetaInformation(url, result.Name, result.Description, "", result.PrimaryImageOfPage?.ContentUrl, "");
}
}
}
catch (Exception ex)
{
// TODO: We should probably log this somewhere...
return new MetaInformation(url)
{
HasError = true,
ExternalPageError = ex is WebException
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment