I'm trying to implement a code in C# that posts to LinkedIn's feed, and I already did it using Postman and it worked fine after generating a token that is valid for 60 days. The problem is that I'm having issues when running the code using C# and when it hits this line:
var httpResponse = await client.PostAsync(builder.Uri, httpContent);
it stucks and keeps running forever, so far I waited for 25 mins. and it didn't work at all.
Here is how I did it in Postman:
Header Header
Body body
Here is how I did it in C#:
public async Task<bool> Post(ObjectToBind post)
{
string Body = "";
try
{
using (StreamReader reader = new StreamReader(AppDomain.CurrentDomain.BaseDirectory + @"\SocialMediaModels\Provider\PostLinkedInTemplate.json"))
{
Body = reader.ReadToEnd();
}
Body = Body.Replace("[person_id]", Settings.PersonId).Replace("[text_value]", Settings.ShareCommentary).Replace("[description_value]", Settings.Description).Replace("[url_value]", Settings.OriginalUrl).Replace("[title_value]", Settings.Title);
using (var client = new HttpClient { Timeout = TimeSpan.FromSeconds(30) })
{
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {Settings.Token}");
client.DefaultRequestHeaders.Add("X-Restli-Protocol-Version", "2.0.0");
var builder = new UriBuilder(new Uri("https://api.linkedin.com/v2/ugcPosts"));
var httpContent = new StringContent(Body, Encoding.UTF8, "application/json");
var httpResponse = await client.PostAsync(builder.Uri, httpContent);
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
return false;
}
return true;
}
Note: I double checked the body and the header params. and all are the same as postman, and it never hits the catch block and also I added a break-point inside that block and as i wrote, when it hits that line it stucks in there.
================ UPDATE ====================
Here is where I'm calling the method from:
public static async Task<List<PostResult>> ProcessPosts(List<ObjectToBind> objects)
{
ISocialProvider socialProvider = null;
List<PostResult> postResults = null;
string Message = "";
bool result;
try
{
if (objects != null)
{
var postRes = new PostResult();
foreach (var post in objects)
{
postRes.language = post.Language;
if (post.DatePostedToLinkedIn == null && post.PostToLinkedIn)
{
socialProvider = new LinkedIn();
// HERE IT IS
result = await socialProvider.Post(post);
postRes.SuccessfyllyPostedToLinkedIn = result;
postRes.PostedToLinkedInOn = result ? DateTime.Now : DateTime.MinValue;
postRes.LinkedInMessage = Message;
}
}
}
return postResults;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return postResults;
}
}