Skip to main content
Solved

HttpClient Token Request in .NET Framework

  • October 14, 2024
  • 2 replies
  • 62 views

adriangavino45
Freshman I
Forum|alt.badge.img

Hello all,

I am currently implementing token retrieval using HttpClient in the .NET Framework and have encountered an issue. I am using the SendAsync method to send the username and password in the JSON body as part of the request, but I'm experiencing difficulties with the token acquisition.

Below is a snippet of the code I am using for this operation:

public PXAction<INRegister> PrenderAntena;

[PXButton]

[PXUIField(DisplayName = "Prender Antena", MapEnableRights = PXCacheRights.Select, MapViewRights = PXCacheRights.Select, Enabled = true)]

protected virtual IEnumerable prenderAntena(PXAdapter adapter)

{

    Prueba();

    return adapter.Get();

}



public async Task Prueba()

{



// Use specific classes to define the JSON structure

    var credentials = new Credentials

    {

        usuario = new FieldValue { value = "MyUser" },

        contraseña = new FieldValue { value = "MyPassword" }

    };

   

    string jsonPayload = JsonConvert.SerializeObject(credentials, Formatting.Indented);

    string url = "MyUrl";



    var handler = new WinHttpHandler();

   

    using (HttpClient client = new HttpClient(handler))

    {

        try

        {

            var requestMessage = new HttpRequestMessage(HttpMethod.Get, url);

            requestMessage.Content = new StringContent(jsonPayload, Encoding.UTF8, "application/json");

   

         // Use await correctly within an async method

            HttpResponseMessage response = await client.SendAsync(requestMessage);

   

            PXTrace.WriteInformation("Estado de la respuesta: " + response.StatusCode.ToString());

   

            if (response.IsSuccessStatusCode)

            {

                string responseContent = await response.Content.ReadAsStringAsync();

                PXTrace.WriteInformation("Respuesta del servidor: " + responseContent.ToString());

   

                var apiResponse = JsonConvert.DeserializeObject<ApiResponse>(responseContent);

                PXTrace.WriteInformation("API key: " + apiResponse.apiKey?.value.ToString());

            }

            else

            {

                string errorResponse = await response.Content.ReadAsStringAsync();

                PXTrace.WriteInformation("Error en la solicitud: " + response.ReasonPhrase.ToString(), "Contenido: " + errorResponse);

            }

        }

        catch (HttpRequestException httpEx)

        {

            PXTrace.WriteInformation("Excepción en la solicitud HTTP : " + httpEx.Message);

        }

        catch (Exception ex)

        {

            PXTrace.WriteInformation("Excepción en la solicitud : " + ex.Message);

        }

    }

}

 

// Class to deserialize the response

public class ApiResponse

{

    public ApiKey apiKey { get; set; }

}



public class ApiKey

{

    public string value { get; set; }

}



// Definition of classes for JSON structure

public class Credentials

{

    public FieldValue usuario { get; set; }

    public FieldValue contraseña { get; set; }

}



public class FieldValue

{

    public string value { get; set; }

}

However, I am receiving an error at the following line of code:

HttpResponseMessage response = await client.SendAsync(requestMessage);

 

To troubleshoot, I created a standalone C# .NET Framework project in Visual Studio with the same code, and it works perfectly. However, I am unable to determine what is missing or causing the issue when running it within Acumatica.

Could you please assist in identifying any potential issues or suggest improvements for successfully obtaining the token?

Thanks!
Regards!

Best answer by Dmitrii Naumov

  1. Make your Prueba method static.
  2. Invoke it like that: graph.LongOperationManager.StartAsyncOperation((ct) => Prueba());
View original
Did this topic help you find an answer to your question?

2 replies

Dmitrii Naumov
Acumatica Moderator
Forum|alt.badge.img+7
  • Acumatica Moderator
  • 629 replies
  • Answer
  • October 15, 2024
  1. Make your Prueba method static.
  2. Invoke it like that: graph.LongOperationManager.StartAsyncOperation((ct) => Prueba());

adriangavino45
Freshman I
Forum|alt.badge.img
  • Author
  • Freshman I
  • 21 replies
  • October 15, 2024

Thanks a lot @Dmitrii Naumov, It Works!

Regards.


Reply


Cookie policy

We use cookies to enhance and personalize your experience. If you accept you agree to our full cookie policy. Learn more about our cookies.

 
Cookie settings