Integrate Facebook Ads Using ASP.NET MVC

This is a sample article to integrate Facebook login using MVC and after creating a login you can fetch data from Facebook Ads accounts. So I used this to collect data for insight, reports, etc.

Step 1

You need to start with Sign in to the Facebook developer.

Step 2

Then you need to create an app. In the Facebook developer account go to the app dashboard then click on my apps and then create an app.

Integrate Facebook Ads using ASP.NET MVC

Step 3

When the app is created. Click on the app and go to the settings then copy the app id and app secret for future use.

Integrate Facebook Ads using ASP.NET MVC

Step 4

Now let's start the coding part.

First, just create a simple MVC project then add a controller to it. In the Index Method, I have added the scope, App Id, redirect URL. This method will return a URL that will redirect us to the Facebook login page.

public ActionResult Index() {
    dynamic parameters = new ExpandoObject();
    parameters.client_id = "enter the client id here"; //app id
    parameters.redirect_uri = "enter the redirect url here";
    parameters.response_type = "code";
    parameters.display = "popup";
    var extendedPermissions = "ads_management,ads_read,instagram_basic,business_management,email,pages_messaging,publish_to_groups,pages_manage_metadata,pages_read_user_content,leads_retrieval,pages_read_engagement,pages_manage_posts,publish_to_groups,pages_manage_ads,instagram_basic,pages_show_list,pages_manage_engagement,read_insights"; {
        parameters.scope = extendedPermissions;
    var _fb = new FacebookClient();
    var url = _fb.GetLoginUrl(parameters);
    return Redirect(url.ToString());

Don't forget to add this redirect URL in the Facebook developer app also, go to your app then Facebook login then settings, you'll see this screen now add the URL in the redirect URL text box and save the changes.

Integrate Facebook Ads using ASP.NET MVC

Now we have to retrieve user profile details.

public ActionResult Login_success() {
    var _fb = new FacebookClient();
    List < object > oList = new List < object > ();
    FacebookOAuthResult oauthResult;
    if (!_fb.TryParseOAuthCallbackUrl(Request.Url, out oauthResult)) {}
    if (oauthResult.IsSuccess) {
        var WebClient = new WebClient();
        Dictionary < string, object > parameters = new Dictionary < string, object > ();
        parameters.Add("client_id", "enter client id here");
        parameters.Add("redirect_uri", "enter redirect uri here");
        parameters.Add("client_secret", "enter client secret here");
        parameters.Add("code", oauthResult.Code);
        dynamic result = _fb.Get("/oauth/access_token", parameters);
        var accessToken = result.access_token;
        _fb.AccessToken = Session["AccessToken"].ToString();
        dynamic me = _fb.Get("me?fields=first_name,middle_name,last_name,id,email");
        string email =;
        string firstname = me.first_name;
        string middlename = me.middle_name;
        string lastname = me.last_name;
        string name = firstname + " " + middlename + " " + lastname;
        string id =;
        FbHelper db = new FbHelper();
        db.save_User_Info(id, name, email, accessToken);
        FormsAuthentication.SetAuthCookie(email, false);
    } else {}
    return View();

That's it. I have used the same user info method to save the id, name, email, and access token of the current user in my database.

public long save_User_Info(string strUserGuid, string strName, string strEmail, string accessToken) {
    long nResult = 0;
    try {
        SqlParameter[] sq = {
            new SqlParameter("@user_guid", strUserGuid),
            new SqlParameter("@user_name", strName),
            new SqlParameter("@user_email", strEmail),
            new SqlParameter("@user_token", accessToken)
        nResult = _helper.ExecuteStoredProcedure("usp_insert_facebook_user_Information", sq);
    } catch (Exception ex) {}
    return nResult;

At first, Facebook gives us basic permission to access profiles, email, etc. To get Facebook ads details like campaign details we need to go to the app review and then permissions and features. There you will see all the permissions, you can take permissions from there for your app. And use the below API requests to retrieve campaigns.

public ActionResult CampaignData() {
    string page_Token = "enter page token here";
    string page_Id = "enter page id here";
    string page_post_id = "enter page post id here";
    string act_ad_id = "enter account act id here";
    string user_Token = "enter user token here";
    string ad_Set_Id = "enter ad set id here";
    var WebClient = new WebClient();
    string user_url = string.Format("" + ad_Set_Id + "/insights?fields=clicks%2Cspend%2Cimpressions%2Creach&access_token=" + user_Token);
    string post_url = string.Format("" + page_Id + "?fields=posts%2Cads_posts&access_token=" + page_Token);
    string post_like_url = string.Format("" + page_post_id + "?fields=likes%2Ccomments%2Cshares%2Creactions%2Ctargeting%2Ctarget&access_token=" + page_Token);
    string page_tagret_url = string.Format("" + act_ad_id + "/adsets?fields=name%2Ctargeting&access_token=" + page_Token);
    string getPostData = WebClient.DownloadString(post_url);
    string getPostActivity = WebClient.DownloadString(post_like_url);
    string getPageTarget = WebClient.DownloadString(page_tagret_url);
    string getUserData = WebClient.DownloadString(user_url);
    DataTable dtPostData = ConvertJsonToDatatableLinq(getPostData);
    var userDataList = JsonConvert.DeserializeObject < FacebookJsonConversion.Root > (getUserData);
    var pageActivity = JsonConvert.DeserializeObject < PostActivityJsonConversion.Root > (getPostActivity);
    var pageTarget = JsonConvert.DeserializeObject < PageTargetJsonConversion.Root > (getPageTarget);
    List < object > postData = new List < object > ();
    return View(postData);

All done..................

Thank You