Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/263.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# ASP.NET中的Twitter登录身份验证:410错误_C#_Asp.net_Twitter_Twitter Oauth - Fatal编程技术网

C# ASP.NET中的Twitter登录身份验证:410错误

C# ASP.NET中的Twitter登录身份验证:410错误,c#,asp.net,twitter,twitter-oauth,C#,Asp.net,Twitter,Twitter Oauth,我正在asp.net中为我的网站实现twitter登录身份验证 单击Twitter登录按钮并授权应用程序后,我会看到以下错误页面: 远程服务器返回错误:(410)已消失。 这是我的密码: .ASPX页面: <asp:ImageButton ID="imgTwitter" runat="server" ImageUrl="~/TwitterSigning.png" OnClick="imgTwitter_Click" /> AppCode/oAuthTwitter.cs: using

我正在asp.net中为我的网站实现twitter登录身份验证

单击Twitter登录按钮并授权应用程序后,我会看到以下错误页面:

远程服务器返回错误:(410)已消失。

这是我的密码:

.ASPX页面:

<asp:ImageButton ID="imgTwitter" runat="server" ImageUrl="~/TwitterSigning.png" OnClick="imgTwitter_Click" />
AppCode/oAuthTwitter.cs

using System;
using System.Collections.Specialized;
using System.Configuration;
using System.IO;
using System.Net;
using System.Web;

namespace oAuthExample
{
public class oAuthTwitter : OAuthBase
{
    #region Method enum

    public enum Method
    {
        GET,
        POST,
        DELETE
    } ;

    #endregion

    public const string REQUEST_TOKEN = "https://api.twitter.com/oauth/request_token";
    public const string AUTHORIZE = "https://api.twitter.com/oauth/authorize";
    public const string ACCESS_TOKEN = "https://api.twitter.com/oauth/access_token";
    private string _callBackUrl = "oob"; // your app link or any other link...

    private string _consumerKey = "";
    private string _consumerSecret = "";
    private string _oauthVerifier = "";
    private string _token = "";
    private string _tokenSecret = "";

    #region Properties

    public string ConsumerKey
    {
        get
        {
            if (_consumerKey.Length == 0)
            {
                _consumerKey = ConfigurationManager.AppSettings["consumerKey"];
            }
            return _consumerKey;
        }
        set { _consumerKey = value; }
    }

    public string ConsumerSecret
    {
        get
        {
            if (_consumerSecret.Length == 0)
            {
                _consumerSecret = ConfigurationManager.AppSettings["consumerSecret"];
            }
            return _consumerSecret;
        }
        set { _consumerSecret = value; }
    }

    public string Token
    {
        get { return _token; }
        set { _token = value; }
    }

    public string TokenSecret
    {
        get { return _tokenSecret; }
        set { _tokenSecret = value; }
    }

    public string CallBackUrl
    {
        get { return _callBackUrl; }
        set { _callBackUrl = value; }
    }

    public string OAuthVerifier
    {
        get { return _oauthVerifier; }
        set { _oauthVerifier = value; }
    }

    #endregion

    /// <summary>
    /// Get the link to Twitter's authorization page for this application.
    /// </summary>
    /// <returns>The url with a valid request token, or a null string.</returns>
    public string AuthorizationLinkGet()
    {
        string ret = null;

        string response = oAuthWebRequest(Method.GET, REQUEST_TOKEN, String.Empty);
        if (response.Length > 0)
        {
            //response contains token and token secret.  We only need the token.
            NameValueCollection qs = HttpUtility.ParseQueryString(response);

            if (qs["oauth_callback_confirmed"] != null)
            {
                if (qs["oauth_callback_confirmed"] != "true")
                {
                    throw new Exception("OAuth callback not confirmed.");
                }
            }

            if (qs["oauth_token"] != null)
            {
                ret = AUTHORIZE + "?oauth_token=" + qs["oauth_token"];
            }
        }
        return ret;
    }

    /// <summary>
    /// Exchange the request token for an access token.
    /// </summary>
    /// <param name="authToken">The oauth_token is supplied by Twitter's authorization page following the callback.</param>
    /// <param name="oauthVerifier">An oauth_verifier parameter is provided to the client either in the pre-configured callback URL</param>
    public void AccessTokenGet(string authToken, string oauthVerifier)
    {
        Token = authToken;
        OAuthVerifier = oauthVerifier;

        string response = oAuthWebRequest(Method.GET, ACCESS_TOKEN, String.Empty);

        if (response.Length > 0)
        {
            //Store the Token and Token Secret
            NameValueCollection qs = HttpUtility.ParseQueryString(response);
            if (qs["oauth_token"] != null)
            {
                Token = qs["oauth_token"];
            }
            if (qs["oauth_token_secret"] != null)
            {
                TokenSecret = qs["oauth_token_secret"];
            }
        }
    }

    /// <summary>
    /// Submit a web request using oAuth.
    /// </summary>
    /// <param name="method">GET or POST</param>
    /// <param name="url">The full url, including the querystring.</param>
    /// <param name="postData">Data to post (querystring format)</param>
    /// <returns>The web server response.</returns>
    public string oAuthWebRequest(Method method, string url, string postData)
    {
        string outUrl = "";
        string querystring = "";
        string ret = "";


        //Setup postData for signing.
        //Add the postData to the querystring.
        if (method == Method.POST || method == Method.DELETE)
        {
            if (postData.Length > 0)
            {
                //Decode the parameters and re-encode using the oAuth UrlEncode method.
                NameValueCollection qs = HttpUtility.ParseQueryString(postData);
                postData = "";
                foreach (string key in qs.AllKeys)
                {
                    if (postData.Length > 0)
                    {
                        postData += "&";
                    }
                    qs[key] = HttpUtility.UrlDecode(qs[key]);
                    qs[key] = UrlEncode(qs[key]);
                    postData += key + "=" + qs[key];
                }
                if (url.IndexOf("?") > 0)
                {
                    url += "&";
                }
                else
                {
                    url += "?";
                }
                url += postData;
            }
        }

        var uri = new Uri(url);

        string nonce = GenerateNonce();
        string timeStamp = GenerateTimeStamp();

        //Generate Signature
        string sig = GenerateSignature(uri,
                                       ConsumerKey,
                                       ConsumerSecret,
                                       Token,
                                       TokenSecret,
                                       CallBackUrl,
                                       OAuthVerifier,
                                       method.ToString(),
                                       timeStamp,
                                       nonce,
                                       out outUrl,
                                       out querystring);

        querystring += "&oauth_signature=" + UrlEncode(sig);

        //Convert the querystring to postData
        if (method == Method.POST || method == Method.DELETE)
        {
            postData = querystring;
            querystring = "";
        }

        if (querystring.Length > 0)
        {
            outUrl += "?";
        }

        ret = WebRequest(method, outUrl + querystring, postData);

        return ret;
    }

    /// <summary>
    /// Web Request Wrapper
    /// </summary>
    /// <param name="method">Http Method</param>
    /// <param name="url">Full url to the web resource</param>
    /// <param name="postData">Data to post in querystring format</param>
    /// <returns>The web server response.</returns>
    public string WebRequest(Method method, string url, string postData)
    {
        HttpWebRequest webRequest = null;
        StreamWriter requestWriter = null;
        string responseData = "";

        webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
        webRequest.Method = method.ToString();
        webRequest.ServicePoint.Expect100Continue = false;
        //webRequest.UserAgent  = "Identify your application please.";
        //webRequest.Timeout = 20000;

        if (method == Method.POST || method == Method.DELETE)
        {
            webRequest.ContentType = "application/x-www-form-urlencoded";

            //POST the data.
            requestWriter = new StreamWriter(webRequest.GetRequestStream());
            try
            {
                requestWriter.Write(postData);
            }
            catch
            {
                throw;
            }
            finally
            {
                requestWriter.Close();
                requestWriter = null;
            }
        }

        responseData = WebResponseGet(webRequest);

        webRequest = null;

        return responseData;
    }

    /// <summary>
    /// Process the web response.
    /// </summary>
    /// <param name="webRequest">The request object.</param>
    /// <returns>The response data.</returns>
    public string WebResponseGet(HttpWebRequest webRequest)
    {
        StreamReader responseReader = null;
        string responseData = "";

        try
        {
            responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
            responseData = responseReader.ReadToEnd();
        }
        catch
        {
            throw;
        }
        finally
        {
            webRequest.GetResponse().GetResponseStream().Close();
            responseReader.Close();
            responseReader = null;
        }

        return responseData;
    }
}
使用系统;
使用System.Collections.Specialized;
使用系统配置;
使用System.IO;
Net系统;
使用System.Web;
名称空间OAuthesample
{
公共类oAuthTwitter:OAuthBase
{
#区域方法枚举
公共枚举法
{
得到,
邮递
删除
} ;
#端区
公用常量字符串请求\u令牌=”https://api.twitter.com/oauth/request_token";
公用常量字符串授权=”https://api.twitter.com/oauth/authorize";
公用常量字符串访问\u令牌=”https://api.twitter.com/oauth/access_token";
私有字符串_callBackUrl=“oob”//您的应用程序链接或任何其他链接。。。
私有字符串_consumerKey=“”;
私有字符串_consumerSecret=“”;
私有字符串_oauthVerifier=“”;
私有字符串_token=“”;
私有字符串_tokenSecret=“”;
#区域属性
公共字符串消费器
{
得到
{
如果(_consumerKey.Length==0)
{
_consumerKey=ConfigurationManager.AppSettings[“consumerKey”];
}
返回消费市场;
}
设置{u consumerKey=value;}
}
公共字符串ConsumerCret
{
得到
{
如果(_consumerSecret.Length==0)
{
_ConsumerCret=ConfigurationManager.AppSettings[“ConsumerCret”];
}
返回消费者信用;
}
设置{u consumerSecret=value;}
}
公共字符串令牌
{
获取{return\u token;}
设置{u令牌=值;}
}
公共字符串令牌密钥
{
获取{return\u tokenSecret;}
设置{u tokenSecret=value;}
}
公共字符串回调URL
{
获取{return\u callBackUrl;}
设置{u callBackUrl=value;}
}
公共字符串OAuthVerifier
{
获取{return\uOAuthVerifier;}
设置{uOAuthVerifier=value;}
}
#端区
/// 
///获取此应用程序的Twitter授权页面链接。
/// 
///具有有效请求令牌或空字符串的url。
公共字符串授权LinkGet()
{
字符串ret=null;
string response=oAuthWebRequest(Method.GET,REQUEST_令牌,string.Empty);
如果(response.Length>0)
{
//响应包含令牌和令牌机密。我们只需要令牌。
NameValueCollection qs=HttpUtility.ParseQueryString(响应);
如果(qs[“oauth_回调_确认”]!=null)
{
如果(qs[“oauth\u回调\u确认”]!=“真”)
{
抛出新异常(“OAuth回调未确认”);
}
}
如果(qs[“oauth_令牌”!=null)
{
ret=AUTHORIZE+“?oauth_令牌=“+qs[“oauth_令牌”];
}
}
返回ret;
}
/// 
///将请求令牌交换为访问令牌。
/// 
///oauth_令牌由Twitter的授权页面在回调之后提供。
///在预配置的回调URL中向客户端提供oauth_验证器参数
public void AccessTokenGet(字符串authToken、字符串oauthVerifier)
{
Token=authToken;
OAuthVerifier=OAuthVerifier;
string response=oAuthWebRequest(Method.GET,ACCESS\u令牌,string.Empty);
如果(response.Length>0)
{
//存储令牌和令牌密钥
NameValueCollection qs=HttpUtility.ParseQueryString(响应);
如果(qs[“oauth_令牌”!=null)
{
令牌=qs[“oauth_令牌”];
}
如果(qs[“oauth\u令牌\u秘密”]!=null)
{
TokenSecret=qs[“oauth_token_secret”];
}
}
}
/// 
///使用oAuth提交web请求。
/// 
///投递
///完整的url,包括查询字符串。
///要发布的数据(查询字符串格式)
///web服务器响应。
公共字符串oAuthWebRequest(方法、字符串url、字符串postData)
{
字符串outUrl=“”;
字符串querystring=“”;
字符串ret=“”;
//设置用于签名的postData。
//将postData添加到查询字符串。
if(method==method.POST | | method==method.DELETE)
{
如果(postData.Length>0)
{
//解码参数并使用oAuth UrlEncode方法重新编码。
NameValueCollection qs=HttpUtility.ParseQueryString(postData);
postData=“”;
foreach(qs.allkey中的字符串键)
{
如果(postData.Length>0)
{
postData+=“&”;
}
qs[key]=HttpUtility.UrlDecode(qs[key]);
qs[key]=UrlEncode(qs[key]);
postData+=key+“=”+qs[key];
}
如果(url.IndexOf(“?”)大于0)
{
url+=“&”;
}
其他的
{
url+=“?”;
}
url+=postData;
}
}
var uri=新的uri(url);
字符串nonce=generateOnce();
字符串时间戳=GenerateTimeStamp();
//生成签名
字符串sig=GenerateSignature(uri,
消费主义,,
消费者信用,
代币
using System;
using System.Collections.Specialized;
using System.Configuration;
using System.IO;
using System.Net;
using System.Web;

namespace oAuthExample
{
public class oAuthTwitter : OAuthBase
{
    #region Method enum

    public enum Method
    {
        GET,
        POST,
        DELETE
    } ;

    #endregion

    public const string REQUEST_TOKEN = "https://api.twitter.com/oauth/request_token";
    public const string AUTHORIZE = "https://api.twitter.com/oauth/authorize";
    public const string ACCESS_TOKEN = "https://api.twitter.com/oauth/access_token";
    private string _callBackUrl = "oob"; // your app link or any other link...

    private string _consumerKey = "";
    private string _consumerSecret = "";
    private string _oauthVerifier = "";
    private string _token = "";
    private string _tokenSecret = "";

    #region Properties

    public string ConsumerKey
    {
        get
        {
            if (_consumerKey.Length == 0)
            {
                _consumerKey = ConfigurationManager.AppSettings["consumerKey"];
            }
            return _consumerKey;
        }
        set { _consumerKey = value; }
    }

    public string ConsumerSecret
    {
        get
        {
            if (_consumerSecret.Length == 0)
            {
                _consumerSecret = ConfigurationManager.AppSettings["consumerSecret"];
            }
            return _consumerSecret;
        }
        set { _consumerSecret = value; }
    }

    public string Token
    {
        get { return _token; }
        set { _token = value; }
    }

    public string TokenSecret
    {
        get { return _tokenSecret; }
        set { _tokenSecret = value; }
    }

    public string CallBackUrl
    {
        get { return _callBackUrl; }
        set { _callBackUrl = value; }
    }

    public string OAuthVerifier
    {
        get { return _oauthVerifier; }
        set { _oauthVerifier = value; }
    }

    #endregion

    /// <summary>
    /// Get the link to Twitter's authorization page for this application.
    /// </summary>
    /// <returns>The url with a valid request token, or a null string.</returns>
    public string AuthorizationLinkGet()
    {
        string ret = null;

        string response = oAuthWebRequest(Method.GET, REQUEST_TOKEN, String.Empty);
        if (response.Length > 0)
        {
            //response contains token and token secret.  We only need the token.
            NameValueCollection qs = HttpUtility.ParseQueryString(response);

            if (qs["oauth_callback_confirmed"] != null)
            {
                if (qs["oauth_callback_confirmed"] != "true")
                {
                    throw new Exception("OAuth callback not confirmed.");
                }
            }

            if (qs["oauth_token"] != null)
            {
                ret = AUTHORIZE + "?oauth_token=" + qs["oauth_token"];
            }
        }
        return ret;
    }

    /// <summary>
    /// Exchange the request token for an access token.
    /// </summary>
    /// <param name="authToken">The oauth_token is supplied by Twitter's authorization page following the callback.</param>
    /// <param name="oauthVerifier">An oauth_verifier parameter is provided to the client either in the pre-configured callback URL</param>
    public void AccessTokenGet(string authToken, string oauthVerifier)
    {
        Token = authToken;
        OAuthVerifier = oauthVerifier;

        string response = oAuthWebRequest(Method.GET, ACCESS_TOKEN, String.Empty);

        if (response.Length > 0)
        {
            //Store the Token and Token Secret
            NameValueCollection qs = HttpUtility.ParseQueryString(response);
            if (qs["oauth_token"] != null)
            {
                Token = qs["oauth_token"];
            }
            if (qs["oauth_token_secret"] != null)
            {
                TokenSecret = qs["oauth_token_secret"];
            }
        }
    }

    /// <summary>
    /// Submit a web request using oAuth.
    /// </summary>
    /// <param name="method">GET or POST</param>
    /// <param name="url">The full url, including the querystring.</param>
    /// <param name="postData">Data to post (querystring format)</param>
    /// <returns>The web server response.</returns>
    public string oAuthWebRequest(Method method, string url, string postData)
    {
        string outUrl = "";
        string querystring = "";
        string ret = "";


        //Setup postData for signing.
        //Add the postData to the querystring.
        if (method == Method.POST || method == Method.DELETE)
        {
            if (postData.Length > 0)
            {
                //Decode the parameters and re-encode using the oAuth UrlEncode method.
                NameValueCollection qs = HttpUtility.ParseQueryString(postData);
                postData = "";
                foreach (string key in qs.AllKeys)
                {
                    if (postData.Length > 0)
                    {
                        postData += "&";
                    }
                    qs[key] = HttpUtility.UrlDecode(qs[key]);
                    qs[key] = UrlEncode(qs[key]);
                    postData += key + "=" + qs[key];
                }
                if (url.IndexOf("?") > 0)
                {
                    url += "&";
                }
                else
                {
                    url += "?";
                }
                url += postData;
            }
        }

        var uri = new Uri(url);

        string nonce = GenerateNonce();
        string timeStamp = GenerateTimeStamp();

        //Generate Signature
        string sig = GenerateSignature(uri,
                                       ConsumerKey,
                                       ConsumerSecret,
                                       Token,
                                       TokenSecret,
                                       CallBackUrl,
                                       OAuthVerifier,
                                       method.ToString(),
                                       timeStamp,
                                       nonce,
                                       out outUrl,
                                       out querystring);

        querystring += "&oauth_signature=" + UrlEncode(sig);

        //Convert the querystring to postData
        if (method == Method.POST || method == Method.DELETE)
        {
            postData = querystring;
            querystring = "";
        }

        if (querystring.Length > 0)
        {
            outUrl += "?";
        }

        ret = WebRequest(method, outUrl + querystring, postData);

        return ret;
    }

    /// <summary>
    /// Web Request Wrapper
    /// </summary>
    /// <param name="method">Http Method</param>
    /// <param name="url">Full url to the web resource</param>
    /// <param name="postData">Data to post in querystring format</param>
    /// <returns>The web server response.</returns>
    public string WebRequest(Method method, string url, string postData)
    {
        HttpWebRequest webRequest = null;
        StreamWriter requestWriter = null;
        string responseData = "";

        webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
        webRequest.Method = method.ToString();
        webRequest.ServicePoint.Expect100Continue = false;
        //webRequest.UserAgent  = "Identify your application please.";
        //webRequest.Timeout = 20000;

        if (method == Method.POST || method == Method.DELETE)
        {
            webRequest.ContentType = "application/x-www-form-urlencoded";

            //POST the data.
            requestWriter = new StreamWriter(webRequest.GetRequestStream());
            try
            {
                requestWriter.Write(postData);
            }
            catch
            {
                throw;
            }
            finally
            {
                requestWriter.Close();
                requestWriter = null;
            }
        }

        responseData = WebResponseGet(webRequest);

        webRequest = null;

        return responseData;
    }

    /// <summary>
    /// Process the web response.
    /// </summary>
    /// <param name="webRequest">The request object.</param>
    /// <returns>The response data.</returns>
    public string WebResponseGet(HttpWebRequest webRequest)
    {
        StreamReader responseReader = null;
        string responseData = "";

        try
        {
            responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
            responseData = responseReader.ReadToEnd();
        }
        catch
        {
            throw;
        }
        finally
        {
            webRequest.GetResponse().GetResponseStream().Close();
            responseReader.Close();
            responseReader = null;
        }

        return responseData;
    }
}
url = "http://api.twitter.com/1.1/account/verify_credentials.xml";
                               ^^ -- this