Accessing Facebook API using C#

Another quick video tutorial from me. Here, we will focus on implementing our own “SDK” responsible for handling the Facebook Graph API using C# and .NET Core (of course you can achieve the same result on the full .NET platform).

If you’re just like me targeting the .NET Core, most likely you realized that Facebook SDK for .NET is not really being supported, at least currently, based on the latest date of the master branch update. And of course the same does apply to the NuGet packages.

Thus, we’re kinda on our own, however, it turns out that accessing the Graph API is quite easy. All we need to do is to make use of the HttpClient or any other type that is responsible for handling the HTTP requests. Let’s jump right into the code:

C#

1

2

3

4

5

6

7

8

9

10

11

publicclassAccount

{

publicstringId{get;set;}

publicstringName{get;set;}

publicstringEmail{get;set;}

publicstringLocale{get;set;}

publicstringUserName{get;set;}

publicstringFirstName{get;set;}

publicstringLastName{get;set;}

publicstringGender{get;set;}

}

The Account basically represents the user account in the Facebook. Please note that you may include there as many more properties as you wish.

The FacebookClient is responsible for handling the POST and GET requests to the Facebook API. Quite straightforward code, no magic here, just keep in mind to add a reference to the Newtonsoft.Json package.

Our FacebookService is where the true “business logic” lays in. It does make use of the underlying FacebookClient in order to execute the HTTP requests to the specified endpoints using some additional arguments.

And finally, our actual application makes use of the FacebookService in order to get our Facebook account and post a message onto our wall. Just remember to get your access token here and mark the needed permissions. And as you may have already noticed, it’s a trivial console application, therefore the Task.WaitAll() is being invoked.

It wasn’t that difficult after all, was it? You can download the source code of this sample application by clicking here.