Azure Cognitive Services - почему у меня нет доступа к сервису?(Ошибка 401) - PullRequest
0 голосов
/ 09 ноября 2018

Я пишу веб-приложение .Net Core, в котором я использую Azure - Computer Vision .

Я делаю все как показано здесь:

https://docs.microsoft.com/pl-pl/azure/cognitive-services/computer-vision/vs-computer-vision-connected-service

и моя проблема:

Результаты Computer Vision API:

{"statusCode": 401, "message": "Доступ запрещен из-за неверного ключа подписки. Убедитесь, что вы предоставили действительный ключ для активной подписки." }

Я не знаю, что не так. У меня есть подходящий ключ и правильная конечная точка. Я также проверил все, что здесь:

https://blogs.msdn.microsoft.com/kwill/2017/05/17/http-401-access-denied-when-calling-azure-cognitive-services-apis/

Вот мой код:

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        // TODO: Change this to your image's path on your site. 
        string imagePath = @"images/family.jpg";

        // Enable static files such as image files. 
        app.UseStaticFiles();

        string visionApiKey = "71a481e3473440d18c586a038365bd79";
        string visionApiEndPoint = "ComputerVisionAPI_ServiceEndPoint";

        HttpClient client = new HttpClient();

        // Request headers.
        // client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", visionApiKey);
        client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "71a481e3473440d18c586a038365bd79");

        // Request parameters. A third optional parameter is "details".
        string requestParameters = "visualFeatures=Categories,Description,Color&language=en";

        // Assemble the URI for the REST API Call.
       // string uri = visionApiEndPoint + "/analyze" + "?" + requestParameters;
        string uri = "https://westus.api.cognitive.microsoft.com/vision/v1.0" + "/analyze" + "?" + requestParameters;


        HttpResponseMessage response;

        // Request body. Posts an image you've added to your site's images folder. 
        var fileInfo = env.WebRootFileProvider.GetFileInfo(imagePath);
        byte[] byteData = GetImageAsByteArray(fileInfo.PhysicalPath);

        string contentString = string.Empty;
        using (ByteArrayContent content = new ByteArrayContent(byteData))
        {
            // This example uses content type "application/octet-stream".
            // The other content types you can use are "application/json" and "multipart/form-data".
            content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

            // Execute the REST API call.
            response = client.PostAsync(uri, content).Result;

            // Get the JSON response.
            contentString = response.Content.ReadAsStringAsync().Result;
        }

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.Run(async (context) =>
        {
            await context.Response.WriteAsync("<h1>Cognitive Services Demo</h1>");
            await context.Response.WriteAsync($"<p><b>Test Image:</b></p>");
            await context.Response.WriteAsync($"<div><img src=\"" + imagePath + "\" /></div>");
            await context.Response.WriteAsync($"<p><b>Computer Vision API results:</b></p>");
            await context.Response.WriteAsync("<p>");
            await context.Response.WriteAsync(JsonPrettyPrint(contentString));
            await context.Response.WriteAsync("<p>");
        });
    }

1 Ответ

0 голосов
/ 09 ноября 2018

Вы должны использовать тот же регион в вызове API REST, который вы использовали для получения ключей подписки.

Сначала вы должны найти местоположение вашей подписки . Чтобы найти местоположение вашего региона подписки, вы должны перейти в Cognitive Services -> Properties под меткой Location, вы найдете свой регион подписки. Увидеть ниже.

Секунда Вы должны найти правильную конечную точку, чтобы позвонить на . Например, если я хочу позвонить в API Computer Vision, мое местоположение - Восток США, я буду использовать либо клавишу 1, либо 2, тогда я буду использовать следующую конечную точку Восток США - https://eastus.api.cognitive.microsoft.com/face/v1.0/detect

Теперь вы сможете получить доступ к API.

Для получения более подробной информации об устранении неполадок, вы можете обратиться к этой статье и этой one .

...