我正在尝试用C#实现代码,该代码发布到LinkedIn的feed中,我已经使用Postman进行了编码,并且在生成有效期为60天的令牌后,它可以正常工作。 问题是,当我使用C#运行代码并碰到此行时遇到问题:
var httpResponse = await client.PostAsync(builder.Uri, httpContent);
它卡住了,并一直运行下去,到目前为止,我等了25分钟。而且根本没有用。
这是我在邮递员中所做的事情:
标题 Header
身体 body
这是我在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;
}
注意:我仔细检查了正文和标题参数。而且都和邮递员一样,它从不碰到catch块,并且我在那个块内添加了一个断点,正如我所写的,当它碰到那条线时,它就卡在了那里。
================更新==================
这是我从以下位置调用方法的地方:
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;
}
}