Use LinkedIn Rest API in ASP.NET MVC
You can use LinkedIn API to access people, companies etc information from LinkedIn.
Visit https://developer.linkedin.com/ for LinkedIn API details.
Here I am describing how you can use LinkedIn Rest API from Asp.net MVC.
First of all you need to be authenticated to use LinkedIn API. You can visit https://developer.linkedin.com/documents/authentication for Authentication details.
For authentication it is better to use any open source OAuth project. For .Net you can use Hommock, DevDefined.OAuth etc.
I have used Hommock for the authentication purpose. You will get the details of Hommock here in https://github.com/danielcrenna/hammock.
To use Hommock you need to download the source from https://github.com/danielcrenna/hammock.
You can do it by any git client like(git extension, tortize git etc.) or from command line.
So after getting the Hommock.dll you need to add a reference to it in your project.
Here is the code to authenticate and made call to my LinkedInService API.
You need to get API keys from https://www.linkedin.com/secure/developer
Please put keys in web.config
<add key="ConsumerKey" value="your_key"/>;
<add key="ConsumerSecret" value="your_secret_key"/>
LinkedinController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Hammock;
using Hammock.Authentication.OAuth;
using System.Configuration;
using Hammock.Web;
using MvcLinkedInApplication.LinkedIn;
namespace MvcLinkedInApplication.Controllers
{
[HandleError]
public class LinkedInController : Controller
{
public ActionResult index()
{
return AuthenticateToLinkedIn();
}
static string token_secret = "";
public ActionResult AuthenticateToLinkedIn()
{
var credentials = new OAuthCredentials
{
CallbackUrl = "http://localhost/home/callback",
ConsumerKey = ConfigurationManager.AppSettings["ConsumerKey"],
ConsumerSecret = ConfigurationManager.AppSettings["ConsumerSecret"],
Verifier = "123456",
Type = OAuthType.RequestToken
};
var client = new RestClient { Authority = "https://api.linkedin.com/uas/oauth", Credentials = credentials };
var request = new RestRequest { Path = "requestToken" };
RestResponse response = client.Request(request);
token = response.Content.Split('&').Where(s => s.StartsWith("oauth_token=")).Single().Split('=')[1];
token_secret = response.Content.Split('&').Where(s => s.StartsWith("oauth_token_secret=")).Single().Split('=')[1];
Response.Redirect("https://api.linkedin.com/uas/oauth/authorize?oauth_token=" + token);
return null;
}
string token = "";
string verifier = "";
public ActionResult Callback()
{
token = Request["oauth_token"];
verifier = Request["oauth_verifier"];
var credentials = new OAuthCredentials
{
ConsumerKey = ConfigurationManager.AppSettings["ConsumerKey"],
ConsumerSecret = ConfigurationManager.AppSettings["ConsumerSecret"],
Token = token,
TokenSecret = token_secret,
Verifier = verifier,
Type = OAuthType.AccessToken,
ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
SignatureMethod = OAuthSignatureMethod.HmacSha1,
Version = "1.0"
};
var client = new RestClient { Authority = "https://api.linkedin.com/uas/oauth", Credentials = credentials, Method = WebMethod.Post };
var request = new RestRequest { Path = "accessToken" };
RestResponse response = client.Request(request);
string content = response.Content;
string accessToken = response.Content.Split('&').Where(s => s.StartsWith("oauth_token=")).Single().Split('=')[1];
string accessTokenSecret = response.Content.Split('&').Where(s => s.StartsWith("oauth_token_secret=")).Single().Split('=')[1];
var company = new LinkedInService(accessToken, accessTokenSecret).GetCompany(162479);
// Some commented call to API
//company = new LinkedInService(accessToken, accessTokenSecret).GetCompanyByUniversalName("linkedin");
// var companies = new LinkedInService(accessToken, accessTokenSecret).GetCompaniesByEmailDomain("apple.com");
// var companies1 = new LinkedInService(accessToken, accessTokenSecret).GetCompaniesByEmailDomain("linkedin.com");
// var companies2= new LinkedInService(accessToken, accessTokenSecret).GetCompaniesByIdAnduniversalName("162479", "linkedin");
//var people = new LinkedInService(accessToken, accessTokenSecret).GetPersonById("f7cp5sKscd");
//var people = new LinkedInService(accessToken, accessTokenSecret).GetCurrentUser();
//string url = Url.Encode("http://bd.linkedin.com/pub/rakibul-islam/37/522/653");
//var people = new LinkedInService(accessToken, accessTokenSecret).GetPeoPleByPublicProfileUrl(url);
//var peopleSearchresult = new LinkedInService(accessToken, accessTokenSecret).SearchPeopleByKeyWord("Princes");
var peopleSearchresult = new LinkedInService(accessToken, accessTokenSecret).GetPeopleByFirstName("Mizan");
String companyName = company.Name;
return Content(companyName);
}
}
}
Bellow is the code for LinkedInService
LinkedInService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Hammock;
using Hammock.Authentication.OAuth;
using System.Configuration;
using Hammock.Web;
using System.Xml.Serialization;
using System.IO;
using System.Xml;
using System.Text;
namespace MvcLinkedInApplication.LinkedIn
{
public class LinkedInService
{
private const string URL_BASE = "http://api.linkedin.com/v1";
public static string ConsumerKey { get { return ConfigurationManager.AppSettings["ConsumerKey"]; } }
public static string ConsumerKeySecret { get { return ConfigurationManager.AppSettings["ConsumerSecret"]; } }
public string AccessToken { get; set; }
public string AccessTokenSecret { get; set; }
public LinkedInService(string accessToken, string accessTokenSecret)
{
this.AccessToken = accessToken;
this.AccessTokenSecret = accessTokenSecret;
}
private OAuthCredentials AccessCredentials
{
get
{
return new OAuthCredentials
{
Type = OAuthType.AccessToken,
SignatureMethod = OAuthSignatureMethod.HmacSha1,
ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
ConsumerKey = ConsumerKey,
ConsumerSecret = ConsumerKeySecret,
Token = AccessToken,
TokenSecret = AccessTokenSecret
};
}
}
#region Helper
private RestResponse GetResponse(string path)
{
var client = new RestClient()
{
Authority = URL_BASE,
Credentials = AccessCredentials,
Method = WebMethod.Get
};
var request = new RestRequest { Path = path };
return client.Request(request);
}
private T Deserialize(string xmlContent)
{
MemoryStream memoryStream = new MemoryStream(Encoding.ASCII.GetBytes(xmlContent));
XmlSerializer deserializer = new XmlSerializer(typeof(T));
return (T)deserializer.Deserialize(new StringReader(xmlContent));
}
#endregion
#region People Information
public Person GetCurrentUser()
{
var response = GetResponse("people/~");
return Deserialize(response.Content);
}
public Person GetPersonById(string id)
{
var response = GetResponse("people/id=" + id.ToString());
return Deserialize(response.Content);
}
public Person GetPersonByPublicProfileUrl(string url)
{
var response = GetResponse("people::(url=" + url + ")");
return Deserialize(response.Content);
}
public PeopleSearchresult SearchPeopleByKeyWord(string keyword)
{
var response = GetResponse("people-search?keywords=" + keyword);
return Deserialize(response.Content);
}
public PeopleSearchresult GetPeopleByFirstName(string firstName)
{
var response = GetResponse("people-search?first-name=" + firstName);
return Deserialize(response.Content);
}
public PeopleSearchresult GetPeopleByLastName(string lastname)
{
var response = GetResponse("people-search?last-name=" + lastname);
return Deserialize(response.Content);
}
public PeopleSearchresult GetPeopleBySchoolName(string schoolName)
{
var response = GetResponse("people-search?school-name=" + schoolName);
return Deserialize(response.Content);
}
#endregion
#region Company information
public Company GetCompany(int id)
{
var response = GetResponse("companies/" + id.ToString());
return Deserialize(response.Content);
}
public Company GetCompanyByUniversalName(string universalName)
{
var response = GetResponse("companies/universal-name=" + universalName);
return Deserialize(response.Content);
}
public CompanyCollection GetCompaniesByEmailDomain(string emailDomain)
{
var response = GetResponse("companies?email-domain=" + emailDomain);
return Deserialize(response.Content);
}
public CompanyCollection GetCompaniesByIdAnduniversalName(string id, string universalName)
{
var response = GetResponse("companies::(" + id + ",universal-name=" + universalName + ")");
return Deserialize(response.Content);
}
#endregion
}
}
I have converted the results into objects bellow
Company.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Serialization;
using System.Collections.ObjectModel;
namespace MvcLinkedInApplication.LinkedIn
{
[Serializable, XmlRoot("company")]
public class Company
{
[XmlElement("id")]
public int Id { get; set; }
[XmlAttribute("key")]
public string Key { get; set; }
[XmlElement("name")]
public string Name { get; set; }
}
[Serializable, XmlRoot("companies")]
public class CompanyCollection
{
[System.Xml.Serialization.XmlElementAttribute("company")]
public Company[] Companies { get; set; }
}
}
People.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Serialization;
namespace MvcLinkedInApplication.LinkedIn
{
[Serializable, XmlRoot("person")]
public class Person
{
[XmlElement("id")]
public string id { get; set; }
[XmlElement("first-name")]
public string FirstName { get; set; }
[XmlElement("last-name")]
public string LastName { get; set; }
[XmlElement("headline")]
public string headLine { get; set; }
[XmlElement("url")]
public string ProfileUrl { get; set; }
}
[Serializable]
public class People
{
[System.Xml.Serialization.XmlElement("person")]
public Person[] Persons { get; set; }
[XmlAttribute("total")]
public int Total { get; set; }
[XmlAttribute("count")]
public int Count { get; set; }
[XmlAttribute("start")]
public int Start { get; set; }
}
[Serializable, XmlRoot("people-search")]
public class PeopleSearchresult
{
[XmlElement("people")]
public People People { get; set; }
[XmlElement("num-results")]
public int Count { get; set; }
}
}
Thank you! This example helped me a lot.
@victor: Welcome
Thanks for posting this, it was very helpful. I’m still coming up to speed on the OAuth stuff, but here is a suggestion to simplify parsing the response:
var contents = HttpUtility.ParseQueryString(response.Content);
var accessToken = contents["oauth_token"];
var accessTokenSecret = contents["oauth_token_secret"];
@Adam: Thanks for your suggestion.
I’m getting an error from LinkedIn when I use the next line:
var companies = new LinkedInService(accessToken, accessTokenSecret).GetCompaniesByEmailDomain(“apple.com”);
I’m getting the next error:
-
400
1329838521783
M6MRP53NGQ
0
Invalid company query request
What is going wrong? I personally think it is going wrong on the questionmark.
Cheers!
the Hammock type of namespace could not be found error will be occurred plz can you possible to send to me that dll files please……
I want to develop import contacts from linkedin to asp.net c# application,show me solution.
The above example contains the solution for you.
Are you facing any problem with this?
hi, i am getting error on : string accessTokenSecret = response.Content.Split(‘&’).Where(s => s.StartsWith(“oauth_token_secret=”)).Single().Split(‘=’)[1];
Sequence contains no elements, please help.
Thanks
Hi,
I have written this example quite earlier and was working fine.
Check that you are getting the response correctly.
For more help you need to send me the code.
Thanks
Mizan
Thanks for the reply,
Now its working fine. But i want to know how to get users ID, profile picture and connection list for logged in users.
Thanks
Hi Ashik,
How you have solved this problem (Sequence contains no elements)
Thanks
Hi,
I am getting this error while deseriazing The type arguments for method ‘LinkedInService.Deserialize(string)’ cannot be inferred from the usage. Try specifying the type arguments explicitly.
Hi,
I get an runtime error “You must specify the token” I have configured the consumerkey and consumersecret in my web.config but still I get the above error.
I am trying to use the code. but i am getting a error like ” The type or namespace name ‘T’ could not be found ” i added System.Collections.Generic also
But Still showing error . can any one help?
Change your code as below…
private T Deserialize(string xmlContent)
{
MemoryStream memoryStream = new MemoryStream(Encoding.ASCII.GetBytes(xmlContent));
XmlSerializer deserializer = new XmlSerializer(typeof(T));
return (T)deserializer.Deserialize(new StringReader(xmlContent));
}
and all other methods ‘returs’ with on that functions return type
ex:
public Person GetCurrentUser()
{
var response = GetResponse(“people/~”);
return Deserialize(response.Content);
}
Apenas para teste copiei e colei, porém a aplicação não roda, aparece um monde de erros
como por exemplo:
corda accessToken = response.Content.Split ( ‘e’ ) Onde (s => s.StartsWith (. “oauth_token =” )) Individual () Split (.. ‘=’ ) [1];
70
corda accessTokenSecret = response.Content.Split ( ‘e’ ) Onde (s => s.StartsWith (. “oauth_token_secret =” )) Individual () Split (.. ‘=’ ) [1];
71
72
var = empresa nova LinkedInService (accessToken, accessTokenSecret) GetCompany (162.479).;
Thanks your intruction. I have get code and try to run in my app. Almost is fine, but how can i get email or full profile?
( Can you show me the way to get it?
Great post – there’s not a lot on this subject in the .Net space, so your work is highly appreciated. I do however seem to have one nagging difficulty that is in specifying the permission type. I modify the RestRequest on line 35 to add in additional permission, and also
var request = new RestRequest { Path = “requestToken?scope=r_basicprofile+r_emailaddress” };
but when I get to the login page, it doesn’t seem to recognize my request for elevated permission: of your LinkedIn info:
YOUR PROFILE OVERVIEW
Name, photo, headline, and current positions
Any thoughts as to what it might be?
Hi James. I am having the same problem. Did you find any solution for that?
For those who find this very helpful blog post, you might also be interested in checking out https://github.com/SpringSource/spring-net-social-linkedin
@admin: I am trying to use your code, but i’m facing problem at below line
token = response.Content.Split(‘&’).Where(s => s.StartsWith(“oauth_token=”)).Single().Split(‘=’)[1];
it’s saying s and gt does not exist, where exactly we define these variables
Thanks
Ravikumar Bolla.
Check whether your linkedin consumer key and consumersecret key are correct and call back url… ex: http://localhost:51046/Detail/Index