ASP.NET MVC: Get user photo from Facebook

ASP.NET MVC: Get user photo from FacebookHi all. Sometimes you need to get user profile photo from facebook in your web application, it can be “Create User” or “Edit User” pages etc. So, let’s create dummy “Create User” page and try it out!

First of all, we need to add our web application to the Facebook.

1) Go to www.facebook.com

2) In the left sidebar click DEVELOPER link

facebook left sidebar

3) Click “Create New App” button

facebook developers - create new app button

4) Fill “Display Name” and select proper “Category”

facebook developers - settings menu

5) After new app has been created you will get “Dashboard” page.

6) Click “Settings” button in the left sidebar and fill “Display Name” and click “Save Changes” one.

facebook developers - settings menu

 

6) After that you need to hit “Add Platform” one and fill “Site url” field. In my case url is http://local.test-facebook.com, it also can be something like http://localhost:4444

facebook developers - add platform button

 

 

facebook developers - add platform button

 

Please, notice that due to testing purposes, we did not fill “App Domains” field, but in case with your production server you have to fill “App Domains” .

For instance, please take a look how looks settings for this blog with http://powerdotnetcore.com url address:

facebook developers - add platform button

So, at this moment we added our test application to the Facebook and all we need it’s App ID.

Little clarification, right now, we want to create asp.net mvc application where we will have “Get User Photo from Facebook” link and by clicking by this one, we have to get user’s profile photo from facebook and display this one on the page! In addition, we will also add “Create User” button and will send image url to the controller.

Let’s create test asp.net mvc application and add UserViewModel.cs

   
public class UserViewModel
{
    public string FacebookProfileImgUrl { get; set; }
}

to our View add next:

@model TestFacebook.Models.UserViewModel

@using (Html.BeginForm("CreateUser", "Account"))
{
    <img id="user-photo" src="#" style="display: none;" />
    @Html.HiddenFor(m => m.FacebookProfileImgUrl, new { id = "hf-facebook-profile-img-url" })
    <div>
        <a href="javascript:void(0)" onclick="FB.login(setFacebookPhoto, { scope: 'user_photos' });">
            Get User Photo from Facebook
        </a>
    </div>
    <br>
    <div><input type="submit" value="Create User" /></div>
}

and add scripts to the View:

<script>

	//Init facebook functionality by using FB.init() with parameters
	window.fbAsyncInit = function () {
		FB.init({
			appId: 273502729522472, // App ID
			channelUrl: '//' + document.domain + '/fbchannel.html', // Channel File
			status: true, // check login status
			cookie: true, // enable cookies to allow the server to access the session
			xfbml: true  // parse XFBML
		});
	};
	
	// Self-invoking anonymous function that loads facebook SDK
	(function (d) {
		var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
		if (d.getElementById(id)) { return; }
		js = d.createElement('script'); js.id = id; js.async = true;
		js.src = "//connect.facebook.net/en_US/all.js";
		ref.parentNode.insertBefore(js, ref);
	})(document);
	
	function setFacebookPhoto(response) {
	
		if (response.status === 'connected') {
			FB.api('/me/?fields=picture', function (response) {
				$("#hf-facebook-profile-img-url").val(response.picture.data.url);
				$("#user-photo").attr('src', response.picture.data.url).show();
			});
		}
	}
	
</script>

and our action in the AccountController.cs

        
[HttpPost]
public ActionResult CreateUser(UserViewModel model)
{
    using (var webClient = new WebClient())
    {
        byte[] imageBytes = webClient.DownloadData(model.FacebookProfileImgUrl);
        //TODO: Save Photo 
    }
    return View();
}

And explanation of what we have:

When our page gets loaded, we init facebook functionality by using FB.init() with parameters, after we can see self-invoking anonymous function that loads facebook SDK.

setFacebookPhoto(response) method makes request to facebook API, gets user photo, sets url of the image to <img> object on the page and sets value for hf-facebook-profile-img-url hidden field to be able to send image url to the server. In this method we also have to check response.status === ‘connected’, in case when user clicks “Get User Photo from Facebook” link, facebook shows next login window:

facebook login popup

and if someone clicks “Cancel” button, we can get OAuthException: “An active access token must be used to query information about the current user.”, so, that’s why we have to add if(response.status === ‘connected’){}.

CreateUser(UserViewModel model) action gets model with our image url and pulls photo by using webClient, please notice, webClient is disposable, so we need to wrap this one by using statement to make sure that object will be disposed.

Download demo solution (Visual Studio 2013)

  • Devashish Das

    Worked fine for me,I got users display pic.