FacebookOpengraphInputC# Open Graph Example

The following C# .NET example shows how a user might use Opengraph.io to get a website’s title, description, and icon given a URL.  This example makes use of .NET system libraries and NewtonSoft’s popular JSON.NET library to retrieve and parse results from the OpenGraph.io API.  The need to gather information like this is very common when creating an application that posts content onto social media sites such as Facebook (see screenshot to the right) or Linkedin where the user wants to control how the link is displayed.

C# Code

using System;
using System.Net;
using System.IO;
using Newtonsoft.Json;

namespace CSharpDemo
{
	class MainClass
	{
		public static void Main (string[] args)
		{
			var url = "http://cnet.com";
			var urlEncoded = Uri.EscapeDataString(url);

			var requestUrl = "https://opengraph.io/api/1.1/site/" + urlEncoded;

			// Make sure to get your API key!  No need for a CC 
			requestUrl += "?app_id=XXXXXXXXXXXXXXXXXXXXXXXX";

			var request = WebRequest.Create(requestUrl);
			request.ContentType = "application/json;";

			string text;

			var response = (HttpWebResponse)request.GetResponse();

			using (var sr = new StreamReader(response.GetResponseStream()))
			{
				text = sr.ReadToEnd();

				dynamic x = JsonConvert.DeserializeObject(text);

				Console.WriteLine("Title\t\t" + x.hybridGraph.title);
				Console.WriteLine("Description\t" + x.hybridGraph.description);
				Console.WriteLine("Image\t\t" + x.hybridGraph.image);
			}
		}
	}
}

The above code is a console application to keep the code required as small as possible but the same request and parsing approach should work for ASP.NET or MVC applications.

csharpoutput