使用 Google.Apis.DialogFlow.V2 验证请求

Authenticating Request with Google.Apis.DialogFlow.V2

我已将我的 C# DialogFlow 客户端从 Google.Cloud.DialogFlow.V2 升级到 Google.Apis.DialogFlow.v2 但是,我在连接到 DialogFlow 时不断收到 401 错误。

这是我的代码:

Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", cloudKeyFile);
var response = new 
  Google.Apis.Dialogflow.v2.DialogflowService().Projects.Agent.Sessions.DetectIntent(
            new Google.Apis.Dialogflow.v2.Data.GoogleCloudDialogflowV2DetectIntentRequest
            {
                QueryInput = new Google.Apis.Dialogflow.v2.Data.GoogleCloudDialogflowV2QueryInput
                {
                    Text = new Google.Apis.Dialogflow.v2.Data.GoogleCloudDialogflowV2TextInput
                    {
                        Text = queryText,
                        LanguageCode = languageCode
                    }
                }
            },
            $"projects/{ProjectId}/agent/sessions/{sessionId}")
            .Execute();

错误:

Google.Apis.Requests.RequestError 请求缺少必需的身份验证凭据。预期的 OAuth 2 访问令牌、登录 cookie 或其他有效的身份验证凭据。参见 https://developers.google.com/identity/sign-in/web/devconsole-project。 [401]

注意:cloudKeyFile 是一个有效的 auth2 密钥文件,适用于以前的框架。 (Google.Cloud.DialogFlow.V2)

有人可以指导我该怎么做吗?

提前致谢

Dialogflow 的 API 身份验证从 v1 到 v2 发生了重大变化。您需要使用具有适当范围 (https://www.googleapis.com/auth/cloud-platform) 和角色 (Dialogflow API AdminDialogflow API ClientDialogflow API Reader) 的 OAuth2 或 OAuth2 服务帐户,而不是使用客户端和开发人员访问令牌

来源:

好的,通过像这样以编程方式向请求添加凭据找到了解决方案:

var creds = GoogleCredential.FromFile(cloudKeyFile);
var scopedCreds = creds.CreateScoped(DialogflowService.Scope.CloudPlatform);
var response = new DialogflowService(new BaseClientService.Initializer
        {
            HttpClientInitializer = scopedCreds,
            ApplicationName = ProjectId
        }).Projects.Agent.Sessions.DetectIntent(
            new GoogleCloudDialogflowV2DetectIntentRequest
            {
                QueryInput = new GoogleCloudDialogflowV2QueryInput
                {
                    Text = new GoogleCloudDialogflowV2TextInput
                    {
                        Text = queryText,
                        LanguageCode = languageCode
                    }
                }
            },
            $"projects/{ProjectId}/agent/sessions/{sessionId}")
            .Execute();

注意 - 请记住添加相关的范围标志!

清晰的示例: https://developers.google.com/api-client-library/dotnet/guide/batch

根据 Godsayer 的回答,我在使用 c# webclient 时设法通过几行代码实现了此功能。

首先,请确保您已经创建了一个 Google 服务帐户并授予其对 DialogFlow 的相关权限。我需要了解 Intents、Utterances 等,因此授予它 DialogFlow API Admin.

然后,在服务帐户中,我创建了一个新的 Json 密钥并下载了它,将其存储在我的应用程序的本地目录中。

在 visual studio 然后我安装了 Google.Apis.Dialogflow.v2 nuget 包。

在我的控制台应用程序中,我添加了以下代码行并且我在!

using Google.Apis.Auth.OAuth2;
using Google.Apis.Dialogflow.v2;

var credentials = GoogleCredential.FromFile(@"C:\pathtofile\abc123.json");
var scopedCredentials = credentials.CreateScoped(DialogflowService.Scope.CloudPlatform);
    _oAuthToken = scopedCredentials.UnderlyingCredential.GetAccessTokenForRequestAsync().Result;
WebClient webclient = new WebClient();
webclient.Headers.Add(HttpRequestHeader.ContentType, "application/json");
webclient.Headers.Add(HttpRequestHeader.Authorization, $"Bearer {_oAuthToken}");

其他答案对我有用但没有用,可能是因为 API 改变了。这对我有用:

            var dialogFlowConfigurationBytes = BlobManager.GetBytesByBlobUrl("your json path"); // get bytes from file using BlobManager class (utility class created by me, you could get the stream directly)

            var credentials = GoogleCredential.FromStream(new MemoryStream(dialogFlowConfigurationBytes));
            Channel channel = new Channel(IntentsClient.DefaultEndpoint.Host, IntentsClient.DefaultEndpoint.Port, credentials.ToChannelCredentials());
            var client = SessionsClient.Create(channel);

            foreach (var text in texts)
            {
                var response = client.DetectIntent(
                    session: new SessionName(dialogFlowConfiguration.ProjectId, sessionId),
                    queryInput: new QueryInput()
                    {
                        Text = new TextInput()
                        {
                            Text = text,
                            LanguageCode = languageCode
                        }
                    }
                );
            }