C#"无效的提供类型"使用Google服务帐户

时间:2016-09-12 06:52:51

标签: c# google-api google-analytics-api google-api-dotnet-client service-accounts

我不是c#的专家,这是我的第一个使用google api和服务帐户的项目。我遇到了一个我不知道如何解决的问题。此代码适用于2台计算机,但不在3台计算机上。

第3台计算机在尝试运行时出现错误无效的原型错误 选中代码Documentation Google API - Service account

可能是什么问题?

使用过的代码:

string[] scopes = new string[] { AnalyticsService.Scope.AnalyticsReadonly };
var keyFilePath = System.AppDomain.CurrentDomain.BaseDirectory + "www.site.nl-012345678.p12";
string serviceAccountEmail = "name@api-project-000000000000.iam.gserviceaccount.com";
string applicationName = "www.applicationname.nl";
string password = "notasecret";

//loading the Key file<br>
var certificate = new X509Certificate2(keyFilePath, password, X509KeyStorageFlags.Exportable);
var credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
    Scopes = scopes
}.FromCertificate(certificate));

// setup the service
var service = new AnalyticsService(new BaseClientService.Initializer()
{
    HttpClientInitializer = credential,
    ApplicationName = applicationName
});

编辑(添加了堆栈跟踪):

Serverfout in toepassing /.  
Ongeldig providertype opgegeven.
Beschrijving: Er is een onverwerkte uitzondering opgetreden tijdens het uitvoeren van de huidige webaanvraag. Raadpleeg de stacktracering voor meer informatie over deze fout en de oorsprong ervan in de code.

Details van uitzondering: System.Security.Cryptography.CryptographicException: Ongeldig providertype opgegeven.


Fout in bron:


Regel 37:             var certificate = new X509Certificate2(keyFilePath, password, X509KeyStorageFlags.Exportable);
Regel 38:             var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail)
Regel 39:             {
Regel 40:                 Scopes = scopes
Regel 41:             }.FromCertificate(certificate));


Bronbestand: C:\inetpub\wwwroot\git\ttldashboard\ttldashboard\Helpers\GoogleAnalytics.cs    Regel: 39

Stacktracering:


[CryptographicException: Ongeldig providertype opgegeven.
]
   System.Security.Cryptography.Utils.CreateProvHandle(CspParameters parameters, Boolean randomKeyContainer) +5265821
   System.Security.Cryptography.Utils.GetKeyPairHelper(CspAlgorithmType keyType, CspParameters parameters, Boolean randomKeyContainer, Int32 dwKeySize, SafeProvHandle& safeProvHandle, SafeKeyHandle& safeKeyHandle) +94
   System.Security.Cryptography.RSACryptoServiceProvider.GetKeyPair() +136
   System.Security.Cryptography.RSACryptoServiceProvider..ctor(Int32 dwKeySize, CspParameters parameters, Boolean useDefaultKeySize) +203
   System.Security.Cryptography.X509Certificates.X509Certificate2.get_PrivateKey() +240
   Google.Apis.Auth.OAuth2.Initializer.FromCertificate(X509Certificate2 certificate) in C:\Users\cloudsharp\Documents\GitHub\google-api-dotnet-client\Src\Support\GoogleApis.Auth.PlatformServices_Shared\OAuth2\ServiceAccountCredential.cs:115
   ttldashboard.Helpers.GoogleAnalytics.GetAnalyticsService() in C:\inetpub\wwwroot\git\ttldashboard\ttldashboard\Helpers\GoogleAnalytics.cs:39
   ttldashboard.Helpers.GoogleAnalytics.GetGoogleExitClicks(Int32 locatieId, String startDate, String stopDate) in C:\inetpub\wwwroot\git\ttldashboard\ttldashboard\Helpers\GoogleAnalytics.cs:146
   ttldashboard.Controllers.DashboardController.Index() in C:\inetpub\wwwroot\git\ttldashboard\ttldashboard\Controllers\DashboardController.cs:67
   lambda_method(Closure , ControllerBase , Object[] ) +87
   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +229
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +35
   System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +39
   System.Web.Mvc.Async.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult) +67
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +42
   System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +72
   System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +386
   System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +386
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +42
   System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +38
   System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +186
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +38
   System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +29
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +65
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +53
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +36
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +38
   System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +44
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +65
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +38
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +399
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +137


Versiegegevens: Microsoft .NET Framework Versie:4.0.30319; ASP.NET Versie:4.6.1038.0

2 个答案:

答案 0 :(得分:3)

我有同样的问题(我使用的是P12文件)。代码在我的桌面上运行,但是一旦我将其部署到Azure,就会因“无效的提供类型”错误而失败。

我缺少的是:X509KeyStorageFlags.MachineKeySet

像这样:

string sKeyFile = System.Web.Hosting.HostingEnvironment.MapPath("/Keys/" + ServiceAccountKey);
if (!System.IO.File.Exists(sKeyFile))
{
    throw new Exception("Key file can't be found! " + sKeyFile);
}

var certificate = new X509Certificate2(sKeyFile, "notasecret", 
                   X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet);

答案 1 :(得分:2)

这可能是该计算机上证书的加密问题。如果我可以重新创建它,我可能会玩它只是为了看看是什么导致它,但因为我不能在这里找到一个“可能”的方式。

转到Google开发者控制台。下载服务帐户.Json文件而不是服务帐户.p12文件。然后使用此代码

 GoogleCredential credential;
 using (var stream = new FileStream(serviceAccountCredentialFilePath, FileMode.Open, FileAccess.Read))
       {
       credential = GoogleCredential.FromStream(stream)
                    .CreateScoped(scopes);
       }

 // Create the service.
 var service = new AnalyticsService(new BaseClientService.Initializer()
    {
    HttpClientInitializer = credential,
    ApplicationName = "Google Authentication Sample",
    });

如果你真的想知道可能导致它的原因,我会看看是否可以找人来ping。