此行为是设计使然。Twitter 使用 OAuth,这是一种旨在允许用户授权应用程序的协议。这对用户有好处,因为否则,您或其他任何人都可以在他们不知情的情况下代表他们执行操作。
考虑到这一点,唯一的方法是让用户明确授权您的应用程序。这是一个如何使用LINQ to Twitter执行此操作的示例,这是我使用 ASP.NET MVC 编写的。当用户访问您的页面时,您可以有一个按钮将他们重定向到OAuthController
下面的BeginAsync
操作。
using System;
using System.Configuration;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Mvc;
using LinqToTwitter;
namespace MvcDemo.Controllers
{
public class OAuthController : AsyncController
{
public ActionResult Index()
{
return View();
}
public async Task<ActionResult> BeginAsync()
{
//var auth = new MvcSignInAuthorizer
var auth = new MvcAuthorizer
{
CredentialStore = new SessionStateCredentialStore
{
ConsumerKey = ConfigurationManager.AppSettings["consumerKey"],
ConsumerSecret = ConfigurationManager.AppSettings["consumerSecret"]
}
};
string twitterCallbackUrl = Request.Url.ToString().Replace("Begin", "Complete");
return await auth.BeginAuthorizationAsync(new Uri(twitterCallbackUrl));
}
public async Task<ActionResult> CompleteAsync()
{
var auth = new MvcAuthorizer
{
CredentialStore = new SessionStateCredentialStore()
};
await auth.CompleteAuthorizeAsync(Request.Url);
// This is how you access credentials after authorization.
// The oauthToken and oauthTokenSecret do not expire.
// You can use the userID to associate the credentials with the user.
// You can save credentials any way you want - database,
// isolated storage, etc. - it's up to you.
// You can retrieve and load all 4 credentials on subsequent
// queries to avoid the need to re-authorize.
// When you've loaded all 4 credentials, LINQ to Twitter will let
// you make queries without re-authorizing.
//
//var credentials = auth.CredentialStore;
//string oauthToken = credentials.OAuthToken;
//string oauthTokenSecret = credentials.OAuthTokenSecret;
//string screenName = credentials.ScreenName;
//ulong userID = credentials.UserID;
//
return RedirectToAction("Index", "Home");
}
}
}
在用户授权您的应用程序后,Twitter 会将他们重定向回该CompleteAsync
方法。请注意有关如何从auth.CredentialStore
. 将它们保存在您的数据库中,然后在您的服务中检索它们以代表用户拨打电话。
这些凭据不会更改,但用户可能会在未来某个时间取消对您的应用程序的授权 - 届时您需要让他们再次授权。您可以在 LINQ to Twitter ASP.NET 示例页面上获取整个示例代码。