仅应用程序授权只能执行应用程序级别的操作。这与允许您代表用户进行操作的其他授权者不同。逻辑是用户有帐户,但应用程序没有。因此,您不能代表应用程序发推文,因为推文无法分配到任何地方。但是,如果您代表用户发推文,则推文会进入该用户的状态列表(他们的时间线)。
LINQ to Twitter 有各种授权者,您可以通过下载特定于您正在使用的技术的示例来查看它们的使用情况。可下载的源代码也有示例。以下是如何使用 PIN 授权器的示例:
static ITwitterAuthorizer DoPinOAuth()
{
// validate that credentials are present
if (ConfigurationManager.AppSettings["twitterConsumerKey"].IsNullOrWhiteSpace() ||
ConfigurationManager.AppSettings["twitterConsumerSecret"].IsNullOrWhiteSpace())
{
Console.WriteLine("You need to set twitterConsumerKey and twitterConsumerSecret in App.config/appSettings. Visit http://dev.twitter.com/apps for more info.\n");
Console.Write("Press any key to exit...");
Console.ReadKey();
return null;
}
// configure the OAuth object
var auth = new PinAuthorizer
{
Credentials = new InMemoryCredentials
{
ConsumerKey = ConfigurationManager.AppSettings["twitterConsumerKey"],
ConsumerSecret = ConfigurationManager.AppSettings["twitterConsumerSecret"]
},
AuthAccessType = AuthAccessType.NoChange,
UseCompression = true,
GoToTwitterAuthorization = pageLink => Process.Start(pageLink),
GetPin = () =>
{
// this executes after user authorizes, which begins with the call to auth.Authorize() below.
Console.WriteLine("\nAfter authorizing this application, Twitter will give you a 7-digit PIN Number.\n");
Console.Write("Enter the PIN number here: ");
return Console.ReadLine();
}
};
// start the authorization process (launches Twitter authorization page).
auth.Authorize();
return auth;
}
这个方法返回一个 PinAuthorizer 的实例,auth,你可以像这样使用它:
PinAuthorizer auth = DoPinAuth();
var ctx = new TwitterContext(auth);
ctx.UpdateStatus("Hello LINQ to Twitter!");
* 更新 *
前面的代码来自旧版本的 LINQ to Twitter。以下是如何使用较新的异步版本执行此操作的示例:
static IAuthorizer DoPinOAuth()
{
var auth = new PinAuthorizer()
{
CredentialStore = new InMemoryCredentialStore
{
ConsumerKey = ConfigurationManager.AppSettings["consumerKey"],
ConsumerSecret = ConfigurationManager.AppSettings["consumerSecret"]
},
GoToTwitterAuthorization = pageLink => Process.Start(pageLink),
GetPin = () =>
{
Console.WriteLine(
"\nAfter authorizing this application, Twitter " +
"will give you a 7-digit PIN Number.\n");
Console.Write("Enter the PIN number here: ");
return Console.ReadLine();
}
};
return auth;
}
然后你可以像这样使用它:
var auth = DoPinOAuth();
await auth.AuthorizeAsync();
var twitterCtx = new TwitterContext(auth);
await twitterCtx.TweetAsync("Hello LINQ to Twitter!");
有关更多信息,您可以找到文档和源代码。源代码在New\Demos文件夹中有演示。