Samy Sammour
Samy Sammour

Reputation: 2465

Get image information Cognitve Service - Bad Request ASP.NET MVC c#

I am trying to write a code about reading a list of images and get the information from it using Cognitive Service MVC.NET.

I wrote this code:

        public async Task<ActionResult> Index()
        {
            List<string> list = await ReadImages();
            return View(list);
        }
        private async Task<List<string>> ReadImages()
        {
            List<string> list = new List<string>();
            string[] photoEntries = Directory.GetFiles(_photoFolder);
            foreach (string photo in photoEntries)
            {
                list.Add(await GetCaptionAsync(photo));
            }
            return list;
        }

        private async Task<string> GetCaptionAsync(string photo)
        {

            using (var client = new HttpClient())
            {
                var queryString = HttpUtility.ParseQueryString(string.Empty);
                //setup HttpClient
                client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", _apiKey);                
                queryString["visualFeatures"] = "Categories";
                queryString["details"] = "Celebrities";
                queryString["language"] = "en";
                var uri = "https://westus.api.cognitive.microsoft.com/vision/v1.0/analyze?" + queryString;

                HttpResponseMessage response;
                byte[] byteData = Encoding.UTF8.GetBytes(photo);

                using (var content = new ByteArrayContent(byteData))
                {
                    content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                    response = await client.PostAsync(uri, content);
                }

                return response.Content.ToString();
            }
        }

the View is:

@model List<string>
@foreach (var item in Model)
{
    @item
}

I am receiving an Error: 400 Bad request in the line:

response = await client.PostAsync(uri, content);

I do not know what is wrong in this code, anybody please can help me and explain a little about the problem? thank you

Upvotes: 1

Views: 179

Answers (1)

cthrash
cthrash

Reputation: 2973

If you're using c#, you'll find the official client SDK a time-saver, available also in NuGet. In addition to ready-made code to call the service, it will give you concrete types so you don't have to parse the response JSON yourself.

Anyway, your code is mostly correct, but the payload needs to be the file content in binary. So you'll want instead:

byte[] byteData = File.ReadAllBytes(photo);

Also note that you'll want to wait for the response content like this:

return await response.Content.ReadAsStringAsync();

Upvotes: 1

Related Questions