1. ホーム
  2. c#

[解決済み] 認証要求が予期しない結果を返した:404

2022-02-27 18:33:14

質問

例外の詳細 Google.GData.Client.GDataRequestException: 認証リクエストの実行により、予期しない結果が返されました: 404

以下は私のコードです。

protected void Button1_Click(object sender, EventArgs e)
{
    DataSet ds = new DataSet();
    ds.Tables.Add("GmailContacts");
    ds.Tables[0].Columns.Add("EmailID");

    RequestSettings rs = new RequestSettings("Gmail", txtUserName.Value, txtPassword.Value);
    rs.AutoPaging = true;
    ContactsRequest cr = new ContactsRequest(rs);

    Feed<Contact> feed = cr.GetContacts();

    foreach (Contact contact in feed.Entries)
    {
        foreach (Email email in contact.Emails)
        {
            DataRow dr = ds.Tables[0].NewRow();
            dr["EmailID"] = email.Address.ToString();
            ds.Tables[0].Rows.Add(dr);
        }
    }
    GridView1.DataSource = ds;
    GridView1.DataBind();
}

解決方法は?

私自身の解決策を確認する

ステップ

  1. 次のページに移動します。 https://console.developers.google.com/project をクリックし、プロジェクトを作成します。
  2. プロジェクトを選択し、左上のメニューからAPI & authを選択します。
  3. クレデンシャルを選択
  4. Create new Client ID」ボタンでOAuthを作成します(アプリケーションの種類 - Installed Aplication.
  5. 製品名フィールドを埋める
  6. 保存

これで、ネイティブアプリケーション用のクライアントIDが取得できました。 クライアントID。 クライアントの秘密 リダイレクトURI

NuGetからGoogle.Apis.Authをインストールする。

コード

string clientId = null; // https://console.developers.google.com/project/xxx
string clientSecret = null; // https://console.developers.google.com/project/xxx
string accessCode = null; // You will get this code after GetAccessToken method
string redirectUri = null; // https://console.developers.google.com/project/xxx
string applicationName = null; // https://console.developers.google.com/project/xxx
// Scopes https://support.google.com/a/answer/162106?hl=en
string scopes = null; // put your scope like https://www.google.com/m8/feeds/
string accessType = "offline";
string tokenType = "refresh";

OAuth2Parameters parameters = new OAuth2Parameters
{
    ClientId = clientId,
    ClientSecret = clientSecret,
    RedirectUri = redirectUri,
    Scope = scopes,
    AccessType = accessType,
    TokenType = tokenType
};

if (accessCode == null)
{
    string url = OAuthUtil.CreateOAuth2AuthorizationUrl(parameters);
    // Start webbrowser
    Process.Start(url);

    // Load code from web via popup, etc.
    parameters.AccessCode = accessCodeFromWeb;
}

// Check accessToken and refreshToken
// After first acceess with  GetAccessToken you will get that information
if (accessToken == null || refreshToken == null)
{
    OAuthUtil.GetAccessToken(parameters);

    // Save yours accessToken and refreshToken for next connection
    accessToken = parameters.AccessToken;
    refreshToken = parameters.RefreshToken;
}
else
{   
    // Restore your token from config file, etc.
    parameters.AccessToken = accessToken;
    parameters.RefreshToken = refreshToken;
}

RequestSettings rs = new RequestSettings(applicationName, parameters);

return new ContactsRequest(rs);