标签: google-api-dotnet-client

使用刷新令牌进行 C#sharp 身份验证的 Google.Apis 客户端

我正在使用适用于 .NET 的新测试版 Google API 客户端库来加载多个用户的任务列表。它被归类为“已安装的应用程序”(根据谷歌开发控制台),具有多个授权用户帐户。验证一个用户的身份非常简单(使用 google.apis),但我不知道如何使用刷新令牌执行相同的操作,以及如何使用此令牌来获取服务对象。

示例代码:

var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
            GoogleClientSecrets.Load(GoogleTools.GenerateStreamFromString(GoogleTools.Cred)).Secrets,
new[] { TasksService.Scope.Tasks },
"user", CancellationToken.None, new FileDataStore("Tasks.Auth.Store")).Result;         


// Create the service.
service = new TasksService(new BaseClientService.Initializer()
{
     HttpClientInitializer = credential,
     ApplicationName = "Tasks API Sample",
});
Run Code Online (Sandbox Code Playgroud)

我想credential使用刷新令牌构造对象,但我真的迷失了,找不到任何合适的文档。

c# google-api oauth-2.0 google-api-dotnet-client

3
推荐指数
1
解决办法
6101
查看次数

Google Drive API v3 (C# .NET) 按标题搜索文件夹/文件时抛出 RequestError Invalid Value [400]

我正在尝试将文件上传到 Google Drive 到特定文件夹。由于我需要文件夹的 ID(不仅仅是名称)来设置上传目标(文件的父级),我尝试按名称搜索它并从下面的查询中获取第一个返回文件的 ID。我得到一个错误而不是结果:

Google.Apis.Requests.RequestError Invalid Value [400]
Errors [ Message[Invalid Value] Location[q - parameter] Reason[invalid] Domain[global]
at Google.Apis.Requests.ClientServiceRequest`1.Execute()
...
Run Code Online (Sandbox Code Playgroud)

如果我尝试真正搜索任何内容,我会收到此错误或空响应(即对所有目录的查询mimeType='application/vnd.google-apps.folder'返回一个空列表(尽管不会引发错误))。

我的代码的相关片段:

FilesResource.ListRequest request = service.Files.List();
request.Q = "title='test_folder'";
string folderId = request.Execute().Files[0].Id;    // Error occurs here upon execution
...
fileMeta.Parents = new List<string> { folderId };
Run Code Online (Sandbox Code Playgroud)

有趣的是,这个确切的查询适用于 API v2 上的 Google API 测试站点,但不适用于 API v3。获取所有文件夹的查询虽然适用于两者(Google 测试站点上的 v2 和 v3),但我通过我的 .NET 应用程序得到了一个空响应。

PS:文件上传到“我的驱动器”目录工作,驱动服务操作,如设置文件权限工作等。

接受有关检查内容/我搞砸的地方的想法和建议。

c# google-api file-search google-drive-api google-api-dotnet-client

3
推荐指数
1
解决办法
4153
查看次数

尝试访问谷歌分析时指定的提供程序类型无效

每当我们尝试访问 API 以获取当前用户编号时,我们都会收到以下错误。我已经尝试了几件事,但无法深入了解这一点。任何人都可以阐明什么是错误/缺失的吗?

我应该指出,因此在我的本地 PC 上运行得非常好,但在服务器上却失败了。

这是错误:

ConnectToAnalytics 错误:System.Security.Cryptography.CryptographicException:指定的提供程序类型无效。在 System.Security.Cryptography.Utils.CreateProvHandle(CspParameters parameters, Boolean randomKeyContainer) at System.Security.Cryptography.Utils.GetKeyPairHelper(CspAlgorithmType keyType, CspParameters 参数, Boolean randomKeyContainer, Int32 dwKeySize, SafeProvHandle& safeProvHandle, SafeKeyHandle System.safeKeyHandle) .Cryptography.RSACryptoServiceProvider.GetKeyPair() at System.Security.Cryptography.RSACryptoServiceProvider..ctor(Int32 dwKeySize, CspParameters parameters, Boolean useDefaultKeySize) at System.Security.Cryptography.X509Certificates.X509Certificate2.get_PrivateKey() at Google.Apis. OAuth2.ServiceAccountCredential.Initializer。

当我运行代码时抛出此错误:

Public Shared Function GetRealtimeUsers() As String
    Try
        'realtime on site
        Dim gsService As AnalyticsService = Core.ConnectToAnalytics
        Dim RequestRealtime As DataResource.RealtimeResource.GetRequest = gsService.Data.Realtime.[Get]([String].Format("ga:{0}", "xxxxx"), "rt:activeUsers")
        Dim feed As RealtimeData = RequestRealtime.Execute()

        Return Int(feed.Rows(0)(0)).ToString()
    Catch ex As Exception
        Return "QUOTA USED"
    End …
Run Code Online (Sandbox Code Playgroud)

asp.net google-api google-analytics-api google-api-dotnet-client service-accounts

3
推荐指数
1
解决办法
1568
查看次数

Google 日历活动未显示在日历中

我们在 Google 中创建了一个服务帐户并使用日历 API 来添加事件,之前工作正常,在 google 停止该帐户并重新激活它之后,它不起作用

我们尝试了新的服务帐户并逐行调试代码,没有错误,并且还返回创建的事件,但未显示在日历中

        CalendarService service = null;
        var serviceAccountCredentialFilePath = 
        Path.Combine(AppDomain.CurrentDomain.BaseDirectory, 
        "ServiceAccount_Key.json");
        if (Path.GetExtension(serviceAccountCredentialFilePath).ToLower() 
        == ".json")
        {
            GoogleCredential credential;

            string[] scopes = new string[] {
                CalendarService.Scope.Calendar, // Manage your calendars
                CalendarService.Scope.CalendarReadonly // View your Calendars
             };
            using (var stream = new FileStream(serviceAccountCredentialFilePath, FileMode.Open, FileAccess.Read))
            {
                credential = GoogleCredential.FromStream(stream)
                     .CreateScoped(scopes);
            }
            // Create the service.
            service = new CalendarService(new BaseClientService.Initializer
            {
                HttpClientInitializer = credential,
                ApplicationName = "Esoco"
            });
        }
        // End //

        // Insert Event // …
Run Code Online (Sandbox Code Playgroud)

c# google-calendar-api google-api google-api-dotnet-client service-accounts

3
推荐指数
1
解决办法
1846
查看次数

来自C#/.NET服务的Google Play Android Developer API - (400)错误请求

我正在尝试使用Google API .NET Client Library 从我的ASP.NET Web服务器访问Purchase Status API,这是使用Purchase API v1.1的推荐方法.但是,此API 的" 授权"页面建议直接向Google的OAuth2页面发送Web请求,而不是使用相应的客户端库.

好吧,我尝试了两种方法,我想到了所有变化,它们都导致"远程服务器返回错误:(400)错误请求.".

现在我做了什么来达到我的观点.首先,我在授权页面的创建API控制台项目下完成了所有步骤1-8.接下来,我按照那里的描述生成了刷新令牌.在刷新令牌生成期间,我选择了与用于发布我的Android应用程序相同的Google帐户(现在处于已发布的测试版状态).

接下来我在Visual Studio中创建了一个用于测试目的的控制台C#应用程序(可能是控制台应用程序有问题吗?)并尝试使用此代码调用Purchase API(在某些Google API示例中找到):

    private static void Main(string[] args)
    {
        var provider =
            new WebServerClient(GoogleAuthenticationServer.Description)
                {
                    ClientIdentifier = "91....751.apps.googleusercontent.com",
                    ClientSecret = "wRT0Kf_b....ow"
                };
        var auth = new OAuth2Authenticator<WebServerClient>(
            provider, GetAuthorization);

        var service = new AndroidPublisherService(
            new BaseClientService.Initializer()
                {
                    Authenticator = auth,
                    ApplicationName = APP_NAME
                });

        var request …
Run Code Online (Sandbox Code Playgroud)

android google-api in-app-purchase oauth-2.0 google-api-dotnet-client

2
推荐指数
1
解决办法
5259
查看次数

无法在Visual Studio 2010 Express或更高版本上安装Google.Apis.Auth.Mvc软件包

我正在尝试安装NuGet包Google.Apis.Auth.Mvc.这样做,我收到以下错误消息:

Install-Package:"Microsoft.Bcl"的架构版本与NuGet的2.0.30625.9003版本不兼容.请从http://go.microsoft.com/fwlink/?LinkId=213942将NuGet升级到最新版本

我在Google上查看了这条错误消息,而另外一个人在这两个链接中报告了这样的问题(Visual Studio 2012包管理器控制台错误,http://servercoredump.com/question/21766168/visual-studio-2012-package-经理 - 控制台 - 错误)他只是通过卸载和重新安装NuGet来解决它.

我很害怕这样做,因为我担心NuGet可能无法为我拥有的所有IDE下载扩展.我从Visual Studio Express 2008到2013.

有没有人遇到过这条消息,你知道如何解决这个问题吗?

google-api nuget nuget-package google-api-dotnet-client

2
推荐指数
1
解决办法
6018
查看次数

使用 C# 提交站点地图

我正在使用以下代码将站点地图提交给网站管理员工具

Google.GData.WebmasterTools.WebmasterToolsService service = 
    new Google.GData.WebmasterTools.WebmasterToolsService("www.test1.com");
service.setUserCredentials("email", "password");
String lWebsite = "http%3A%2F%2Fwww%2Etest1%2Ecom%2F";
query.Uri = new Uri("https://www.google.com/webmasters/tools/feeds/sites/");

Google.GData.WebmasterTools.SitemapsEntry se = 
    new Google.GData.WebmasterTools.SitemapsEntry();
se.Content.Src = "http://www.test1.com/Sitemap.xml";
se.Content.Type = "text/xml";
Google.GData.WebmasterTools.SitemapsEntry ret = 
    service.Insert(
        new Uri("https://www.google.com/webmasters/tools/feeds/sites/" + lWebsite + "/sitemaps/"), se);
Run Code Online (Sandbox Code Playgroud)

但是这段代码没有运气。任何人都可以提供一些示例代码来提交站点地图吗?

c# oauth google-webmaster-tools google-oauth google-api-dotnet-client

2
推荐指数
1
解决办法
718
查看次数

ASP.NET中的Google API中的redirect_uri_mismatch

我正在尝试使用ASP.NET Web Form在我的YouTube频道上传视频.我创建了开发人员帐户,并使用基于JavaScript的解决方案进行了测试,该解决方案需要每次登录才能上传视频.

我希望我的网站用户直接在我的频道上传视频,并且每个身份验证应该在代码后面,不应提示用户登录.为此,我写了以下课程:

public class UploadVideo
{
    public async Task Run(string filePath)
    {
        string CLIENT_ID = "1111111111111111111111.apps.googleusercontent.com";
        string CLIENT_SECRET = "234JEjkwkdfh1111";
        var youtubeService = AuthenticateOauth(CLIENT_ID, CLIENT_SECRET, "SingleUser");

        var video = new Video();
        video.Snippet = new VideoSnippet();
        video.Snippet.Title = "Default Video Title";
        video.Snippet.Description = "Default Video Description";
        video.Snippet.Tags = new string[] { "tag1", "tag2" };
        video.Snippet.CategoryId = "22"; // See https://developers.google.com/youtube/v3/docs/videoCategories/list
        video.Status = new VideoStatus();
        video.Status.PrivacyStatus = "unlisted"; // or "private" or "public"

        using (var fileStream = new …
Run Code Online (Sandbox Code Playgroud)

asp.net asp.net-mvc google-api google-api-client google-api-dotnet-client

2
推荐指数
1
解决办法
2857
查看次数

请求的身份验证凭据无效。需要 OAuth 2 访问令牌、登录 cookie 或其他有效的身份验证凭据

C#我有一个在 .NET Core 2.2 框架之上编写的控制台应用程序。

我正在尝试使用我的应用程序连接 Google 我的商家 API 来创建帖子

但每次我尝试调用 REST API 时都会收到以下错误

请求的身份验证凭据无效。需要 OAuth 2 访问令牌、登录 cookie 或其他有效的身份验证凭据。请参阅 https://developers.google.com/identity/sign-in/web/devconsole-project

该代码以前可以工作,但由于某种奇怪的原因,它停止了!

这是一个示例,我获取身份验证令牌,然后调用 API 来获取Google 帐户列表。

var credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets
{
    ClientId = "Client ID",
    ClientSecret = "Client Secret",
}, new[] { "https://www.googleapis.com/auth/plus.business.manage" }, "google username", CancellationToken.None);

using (var client = new HttpClient())
{   
    //client.DefaultRequestHeaders.Clear();
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", credential.Token.AccessToken);
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    var c = await client.GetAsync("https://mybusiness.googleapis.com/v4/accounts");
    var accountContentss = await c.Content.ReadAsStringAsync();
    c.EnsureSuccessStatusCode(); …
Run Code Online (Sandbox Code Playgroud)

c# google-api google-oauth google-api-dotnet-client google-my-business-api

2
推荐指数
1
解决办法
7399
查看次数

下载的 Google Drive 文件已损坏 c#

我正在编写一个程序来下载我的 Google Drive 中的所有数据并保存它。问题是,当文件被保存时,它的原始大小会增加(例如,一个大小为 287KB 的 .xls 文件被保存为 87411KB 大小)并且我无法打开它,因为它说它已损坏。大多数文件是 .xls 和 .xlsx 文件。

我遵循了教程以及 Google API 文档。

现在我正在使用以下代码:

public static void GetFilesFromDrive()
        {
            UserCredential credential;

            using (var stream =
                new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
            {
                // The file token.json stores the user's access and refresh tokens, and is created
                // automatically when the authorization flow completes for the first time.
                string credPath = "token.json";
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
                Console.WriteLine("Credential file saved to: …
Run Code Online (Sandbox Code Playgroud)

.net c# google-api google-drive-api google-api-dotnet-client

2
推荐指数
1
解决办法
114
查看次数