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

时间:2018-10-02 12:00:16

标签: dialogflow google-api-client

我已将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)

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

事先感谢

4 个答案:

答案 0 :(得分:1)

Ok通过以编程方式向请求中添加凭据来找到解决方案:

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

答案 1 :(得分:1)

根据Godsayer的回答,在使用c#网络客户端时,我设法用几行代码来完成此工作。

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

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

然后我在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}");

答案 2 :(得分:0)

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

来源:

答案 3 :(得分:0)

其他答案对我很有用,但没有用,可能是因为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
                        }
                    }
                );
            }