从netcore3.1控制台应用访问Azure认知服务时未经授权

问题描述 投票:0回答:1

我有一个netcore控制台应用程序,它正在使用Microsoft.Azure.CognitiveServices.Language.TextAnalytics Nuget程序包中的客户端库来访问Azure的文本分析API。

[尝试访问API时,我收到以下HttpException:

      Unauthorized. Access token is missing, invalid, audience is incorrect (https://cognitiveservices.azure.com), or have expired.
Unhandled exception. System.AggregateException: One or more errors occurred. (Operation returned an invalid status code 'Unauthorized')

[使用Azure函数上托管的完全相同的代码访问相同的API时-一切正常。我无法在文档或其他任何地方找到任何信息。

.net-core azure-functions microsoft-cognitive azure-cognitive-services
1个回答
0
投票

尝试下面的.net核心控制台应用程序代码以使用TextAnalytics SDK:

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.CognitiveServices.Language.TextAnalytics;
using Microsoft.Azure.CognitiveServices.Language.TextAnalytics.Models;
using Microsoft.Rest;

namespace TextAnalysis
{


    class Program
    {
        private static readonly string key = "<your text analyisis service key>";
        private static readonly string endpoint = "<your text analyisis service endpoint>";
        static void Main(string[] args)
        {


            var client = authenticateClient();

            sentimentAnalysisExample(client);
            languageDetectionExample(client);
            entityRecognitionExample(client);
            keyPhraseExtractionExample(client);
            Console.Write("Press any key to exit.");
            Console.ReadKey();
        }

        static TextAnalyticsClient authenticateClient()
        {
            ApiKeyServiceClientCredentials credentials = new ApiKeyServiceClientCredentials(key);
            TextAnalyticsClient client = new TextAnalyticsClient(credentials)
            {
                Endpoint = endpoint
            };
            return client;
        }

        class ApiKeyServiceClientCredentials : ServiceClientCredentials
        {
            private readonly string apiKey;

            public ApiKeyServiceClientCredentials(string apiKey)
            {
                this.apiKey = apiKey;
            }

            public override Task ProcessHttpRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken)
            {
                if (request == null)
                {
                    throw new ArgumentNullException("request");
                }
                request.Headers.Add("Ocp-Apim-Subscription-Key", this.apiKey);
                return base.ProcessHttpRequestAsync(request, cancellationToken);
            }
        }

        static void sentimentAnalysisExample(ITextAnalyticsClient client)
        {
            var result = client.Sentiment("I had the best day of my life.", "en");
            Console.WriteLine($"Sentiment Score: {result.Score:0.00}");
        }

        static void languageDetectionExample(ITextAnalyticsClient client)
        {
            var result = client.DetectLanguage("This is a document written in English.","us");
            Console.WriteLine($"Language: {result.DetectedLanguages[0].Name}");
        }

        static void entityRecognitionExample(ITextAnalyticsClient client)
        {

            var result = client.Entities("Microsoft was founded by Bill Gates and Paul Allen on April 4, 1975, to develop and sell BASIC interpreters for the Altair 8800.");
            Console.WriteLine("Entities:");
            foreach (var entity in result.Entities)
            {
                Console.WriteLine($"\tName: {entity.Name},\tType: {entity.Type ?? "N/A"},\tSub-Type: {entity.SubType ?? "N/A"}");
                foreach (var match in entity.Matches)
                {
                    Console.WriteLine($"\t\tOffset: {match.Offset},\tLength: {match.Length},\tScore: {match.EntityTypeScore:F3}");
                }
            }
        }


        static void keyPhraseExtractionExample(TextAnalyticsClient client)
        {
            var result = client.KeyPhrases("My cat might need to see a veterinarian.");

            // Printing key phrases
            Console.WriteLine("Key phrases:");

            foreach (string keyphrase in result.KeyPhrases)
            {
                Console.WriteLine($"\t{keyphrase}");
            }
        }

    }
}

您可以在Azure门户上找到您的密钥和终结点:enter image description here

结果:enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.