How to login to Google API with Service Account in C# - Invalid Credentials

后端 未结 5 2345
孤独总比滥情好
孤独总比滥情好 2021-02-02 08:58

I\'m beating myself bloody trying to get a simple service acccount login to work in C#, to Google API and Google Analytics. My company is already getting data into Analytics, an

5条回答
  •  一向
    一向 (楼主)
    2021-02-02 09:32

    FOR 2020, the call is made as follows:

    using System;
    using System.Collections.Generic;
    using System.Web.Mvc;
    using Google.Apis.Services;
    using Google.Apis.Auth.OAuth2;
    using System.IO;
    using Google.Apis.Sheets.v4;
    using Google.Apis.Sheets.v4.Data;
    
    namespace SistemasInfinitos.Controllers.Google.Apis.Sample.MVC4
    {
        public class SpreadsheetseController : Controller
        { 
            public ActionResult IndexAPI()
            {
                //accede a las credenciales
                var stream = new FileStream(Server.MapPath("~/quickstart2-9aaf.json"),
                    FileMode.Open
                   // FileAccess.Read//SOLO LECTURA
                    );
                //abre las credenciales
                var credentials = GoogleCredential.FromStream(stream);
    
                //virifica las credenciales
                if (credentials.IsCreateScopedRequired)
                {
                    credentials = credentials.CreateScoped(new string[] { SheetsService.Scope.Spreadsheets });
                }
                ///inicializa la api
            var service = new SheetsService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credentials,
                    ApplicationName = "SistemasInfinitos",
                });
    
                // Define los parametros.  
                String spreadsheetId = "1MKxeqXV5UEMXU2yBe_xi0nwjooLhNN6Vk";
                String range = "Sheet1";
                SpreadsheetsResource.ValuesResource.GetRequest request =service.Spreadsheets.Values.Get(spreadsheetId, range);
                // imprime   
                ValueRange response = request.Execute();
                IList> values = response.Values;
                ViewBag.List = values;
                return View();
            }
        }
    }
    

    and View

    @{
        ViewBag.Title = "IndexAPI";
    }
    
    

    Read Data From Google Live sheet

    @{ foreach (var item in ViewBag.List) { } }
    id Name
    @item[0] @item[1]

提交回复
热议问题