Error return method "public async Task<string>"

Asked

Viewed 249 times

3

When I run the code below, it gives error on this line:

Literal1.Text= ObterEmocoes(imageFilePath);

Is giving this error message:

An object reference is required for the non-static "Program.Get (string)" field, method, or property

Code:

    protected void Button1_Click(object sender, EventArgs e)
    {
        string imageFilePath = @"C:\Users\madureira\Downloads\JRMJ.jpg";
        Literal1.Text= ObterEmocoes(imageFilePath);
    }

    public async Task<string> ObterEmocoes(string imagemBase64)
    {
        HttpResponseMessage respostaHttp;
        string json;
        byte[] bytesImagem = Convert.FromBase64String(imagemBase64);

        string url = "https://brazilsouth.api.cognitive.microsoft.com/face/v1.0/detect";
        string queryString = "returnFaceId=true&returnFaceLandmarks=false&returnFaceAttributes=age,emotion";

        var httpClient = new HttpClient();
        httpClient.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "2b4d806c1cf5467bb8772f86c3fc0a2e");
        using (var conteudoEmBytes = new ByteArrayContent(bytesImagem))
        {
            conteudoEmBytes.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
            respostaHttp = await httpClient.PostAsync($"{url}?{queryString}", conteudoEmBytes);
            json = await respostaHttp.Content.ReadAsStringAsync();
        }
        return json;
    }
}
  • you... translated the error message?

  • 1

    The message is clear, you need to create an instance of the class. The way you are calling the method should be static

1 answer

1


The error in this line is because you need to use keyword await before calling the method.

Literal1.Text= await ObterEmocoes(imageFilePath);

For this you need to mark the method Button1_Click with the keyword async being like this:

protected async void Button1_Click(object sender, EventArgs e)

Implementation:

protected async void Button1_Click(object sender, EventArgs e)
{
    string imageFilePath = @"C:\Users\madureira\Downloads\JRMJ.jpg";
    Literal1.Text= await ObterEmocoes(imageFilePath);
}

Reference

What difference between async Task and void?

In C#, what is the await keyword for?

  • 1

    It worked by doing this and adding the "<%@ Page Async="true ..." in ASP. NET. Thank you very much!!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.