как позвонить в мой API qnamaker с помощью Microsoft.Azure.CognitiveServices.Knowledge.QnAMaker nuget версия 1.0.0 - PullRequest
0 голосов
/ 09 мая 2019

Я начинаю с Microsoft.Azure.CognitiveServices.Knowledge.QnAMaker nuget, и я пытаюсь использовать класс QnAMakerClient () для инициализации нового экземпляра класса QNAMakerClient.

Но этот класс принимает абстрактные параметры: public QnAMakerClient (учетные данные ServiceClientCredentials, обработчики params DelegatingHandler []). Я нашел какое-то решение https://csharp.hotexamples.com/examples/Microsoft.Rest/TokenCredentials/-/php-tokencredentials-class-examples.html, который указывает, как получить токен учетных данных.

Поскольку я новичок в этой концепции, я не знаю, как получить токен учетных данных для моего ServiceClientCredentials.

1 Ответ

1 голос
/ 09 мая 2019

Вы можете создать свой собственный TokenCredentials класс, который наследуется от ServiceClientCredentials , как показано ниже:

 public class TokenCredentials : ServiceClientCredentials
    {
         /// <summary>
        /// The bearer token type, as serialized in an http Authentication header.
        /// </summary>
        private const string BearerTokenType = "Bearer";

       /// <summary>
        /// Gets or sets secure token used to authenticate against Microsoft Azure API. 
        /// No anonymous requests are allowed.
        /// </summary>
        protected ITokenProvider TokenProvider { get; private set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="TokenCredentials"/>
        /// class with the given 'Bearer' token.
        /// </summary>
        /// <param name="token">Valid JSON Web Token (JWT).</param>
        public TokenCredentials(string token)
            : this(token, BearerTokenType)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="TokenCredentials"/>
        /// class with the given token and token type.
        /// </summary>
        /// <param name="token">Valid JSON Web Token (JWT).</param>
        /// <param name="tokenType">The token type of the given token.</param>
        public TokenCredentials(string token, string tokenType) 
            : this(new StringTokenProvider(token, tokenType))
        {
            if (string.IsNullOrEmpty(token))
            {
                throw new ArgumentNullException("token");
            }
            if (string.IsNullOrEmpty(tokenType))
            {
                throw new ArgumentNullException("tokenType");
            }
        }

        /// <summary>
        /// Create an access token credentials object, given an interface to a token source.
        /// </summary>
        /// <param name="tokenProvider">The source of tokens for these credentials.</param>
        public TokenCredentials(ITokenProvider tokenProvider)
        {
            if (tokenProvider == null)
            {
                throw new ArgumentNullException("tokenProvider");
            }

            this.TokenProvider = tokenProvider;
        }

        /// <summary>
        /// Apply the credentials to the HTTP request.
        /// </summary>
        /// <param name="request">The HTTP request.</param>
        /// <param name="cancellationToken">Cancellation token.</param>
        /// <returns>
        /// Task that will complete when processing has completed.
        /// </returns>
        public async override Task ProcessHttpRequestAsync(HttpRequestMessage request,
            CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            if (TokenProvider == null)
            {
                throw new InvalidOperationException(Resources.TokenProviderCannotBeNull);
            }

            request.Headers.Authorization = await TokenProvider.GetAuthenticationHeaderAsync(cancellationToken);
            await base.ProcessHttpRequestAsync(request, cancellationToken);
        }
    }

Этот является хорошим началомпункт для того, чтобы узнать больше о QnAMaker .

Надеюсь, это поможет !!!

...